I have spring-integration-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration" //etc. >
<channel id="inputChannel"/>
<channel id="outputChannel">
<queue capacity="10"/>
</channel>
<service-activator input-channel="inputChannel"
output-channel="outputChannel"
ref="gmailWorker"
method="getGmailMessage"/>
<beans:bean id="gmailWorker" class="GmailWorker"/>
Configuation:
#Configuration
#ImportResource("classpath:spring-integration-config.xml")
public class PropertiesConfig {
}
And GmailWorker:
public class GmailWorker{
public static Message getGmailMessage(Gmail service,String messageId) throws IOException {
Message gmailMessage = service.users().messages().get("me", messageId).execute();
return gmailMessage;
}
}
Now I don't use InputChannel bean. But my application doesn't deployed on tomcat with logs:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.integration.config.ConsumerEndpointFactoryBean#0':
Cannot resolve reference to bean 'org.springframework.integration.config.ServiceActivatorFactoryBean#0' while setting bean property 'handler';
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.integration.config.ServiceActivatorFactoryBean#0':
FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException:
Target object of type [class GmailWorker] has no eligible methods for handling Messages.
How to configure Spring Integration? And how use inputChannel in application?
Your POJO method looks bad for Spring Integration runtime method invocation engine.
Any Spring Integration component gets deal with Message object, which has headers and payload properties.
When it invokes the POJO method it expects some restricted set of arguments on the method:
Whole Message
any other type which may be treated as payload, if there is some appropriate converter on the matter.
#Header as the request for some header in the MessageHeaders
Map<String, Object> as whole set ofMessageHeaders`
If you want get deal with payload and some headers you can mark params with #Payload, #Headers etc..
More info is here.
Related
I have a spring boot application, say A, which has a bean defined in xml:
<bean class="com.learning.MyBean" name="myBean">
<property name="maxAngle" value="360" ></property>
</bean>
Bean is:
public class MyBean {
#Value("${maxAngle}")
public void setMaxAngle(double maxAngle) {
....
}
}
When I run A independently, all is fine. But when I include it as dependency in another spring boot application, then I get error related to injection of maxAngle:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myBean': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'maxAngle' in value "${maxAngle}"
What can be the issue here?
#Value annotation is used to bind properties defined in application.properties or application.yaml.
Try adding maxAngle=360 to application.properties or application.yaml and remove it from bean XML defination
I am totally new to Spring framework, bean injections etc, and working on a project organized in many sub-projects about it.
In the commons subproject, containing all Entities, DAOs, DS, I have a MyDS class implementing IMyDS and containing its EntityManager and DAO :
#PersistenceContext(unitName="myPersistenceUnit")
private EntityManager entityManager;
#Autowired
#Qualifier("myDAO")
private IMyDAO mainDao;
Then, I am trying to call this class from the Web part of my project, like this:
#Autowired
private IMyDS myDS;
// then I try to call a function of IMyDS, and get an error at this line :
protected ActionForward executeAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ReefPresentationException {
myDS.callFunction(form);
}
But it doesn't work, giving me a NullPointerException. So far I've guessed the bean is not correctly injected, so I tried to add some information in my application-context-spring.xml file :
<bean id="myDS" class="com.my.project.service.IMyDS" />
And I get this error :
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myDS' defined in ServletContext resource [/WEB-INF/config/application-context-spring.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.my.project.service.IMyDS]: Specified class is an interface
So I tried instead to declare the class :
<bean id="myDS" class="com.my.project.service.internal.MyDS" />
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myDS' defined in ServletContext resource [/WEB-INF/config/application-context-spring.xml]: Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError
So I really have no idea of what is wrong right now...
Thanks for your help
The errors says it all. You have defined your interface IMyDS as a bean and Spring can't instantiate the interface.
We have a sample app that showcases some things we are doing client side. It pulls in a few internal libraries to get everything functional. It dummies in some hard-coded data so it doesn't have to be concerned with any kind of persistence mechanism.
In some of these libraries that are pulled in, there are spring data jpa repositories. Something like this:
public interface MyLibraryEntityRepository extends JpaRepository<MyLibraryEntity, Long>
{
//...
}
When the server starts up, I get an error like this:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myLibraryEntityRepository': Cannot create inner bean '(inner bean)#788f64f1' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#788f64f1': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' is defined
It can't find the entityManager, but I don't want to have to use an entityManager. So, in an attempt to override the myLibraryEntityRepository bean, I added the following to my Java config:
#Bean
public MyLibraryEntityRepository getMyLibraryEntityRepository()
{
return myDummyImpl();
}
However, this results in the same error.
Is there any way I can override the bean definition for the spring data jpa repository so that I can use my own dummy implementation and not have to configure an entityManager in my app?
You can use #Bean(name="dummyBean") and the in the #Autowired use the annotation #Qualifier("dummyBean")
I have Spring MVC based web application that calls web service. Web service requires http based authentication for every call.I hold web Service Proxy configuration in applicationContext.xml:
<beans...
<bean id="paymentWebService"
class="org.springframework.remoting.jaxws.JaxWsPortProxyFactoryBean">
<property name="customProperties">
<ref local="jaxwsCustomProperties"/>
</property>
<property name="serviceInterface" value="com.azercell.paymentgateway.client.PaymentGatewayWebService"/>
<property name="wsdlDocumentUrl"
value="#{config.wsdlDocumentUrl}"/>
<property name="namespaceUri" value="http://webservice.paymentgateway.azercell.com/"/>
<property name="serviceName" value="PaymentGatewayWebServiceImplService"/>
<property name="portName" value="PaymentGatewayWebServiceImplPort"/>
</bean>
I have instance field for web service port in my controller:
#Controller
public class PaymentController {
#Resource(name = "paymentWebService")
private PaymentGatewayWebService paymentPort;
#ModelAttribute
public void ajaxAttribute(WebRequest request, Model model) {
UtilMethods.authenticationWebServicePort(paymentPort);
...
}
...
#RequestMapping(value = "/massPayment", method = RequestMethod.POST)
public String massPayment(#RequestParam String amount, #RequestParam MultipartFile file, Model model, Locale locale) {
...
WebServiceResponse response = paymentPort.massPayment(UtilMethods.getNewRequestId()
, fileUploader, UtilMethods.getAmountInCoins(amountBigDecimal), null);
...
return SpringView.MASS_PAYMENT.toString(ajaxRequest);
}
}
Code of UtilMethods.authenticationWebServicePort:
public static void authenticationWebServicePort(PaymentGatewayWebService paymentPort) {
String username = (String) RequestContextHolder.currentRequestAttributes().getAttribute(USERNAME_SESSION_VARIABLE_NAME, RequestAttributes.SCOPE_SESSION);
String password = (String) RequestContextHolder.currentRequestAttributes().getAttribute(PASSWORD_SESSION_VARIABLE_NAME, RequestAttributes.SCOPE_SESSION);
BindingProvider prov = (BindingProvider) paymentPort;
prov.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, username);
prov.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);
}
As controllers are singleton objects there occurring problems every time when requests overlap, if to be precisely one user by mistake can use web methods with username and password that belong to another user.
To prevent this I tried to make web service port request scoped in configuration as below:
<bean id="paymentWebService"
class="org.springframework.remoting.jaxws.JaxWsPortProxyFactoryBean" scope="request">
in this case I got error:
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.filterChains': Cannot resolve reference to bean 'org.springframework.security.web.DefaultSecurityFilterChain#0' while setting bean property 'sourceList' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.DefaultSecurityFilterChain#0': Cannot resolve reference to bean 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0' while setting constructor argument with key [2]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0': Cannot resolve reference to bean 'org.springframework.security.authentication.ProviderManager#0' while setting bean property 'authenticationManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authentication.ProviderManager#0': Cannot resolve reference to bean 'org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0': FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authenticationManager': Cannot resolve reference to bean 'myAuthenticationProvider' while setting constructor argument with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myAuthenticationProvider': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'paymentWebService': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
How to create request scoped web service port?
Try to expose current http request to spring. Just add RequestContextListener in your web.xml:
<web-app>
...
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
...
</web-app>
See this entry from official documentation for more details / options.
EDIT. Think about the difference in lifecycle between controller and paymentPort dependency. Controller is always the same, but paymentPort must be refreshed for each new request. So you cann't continue inject it directly. You need to get fresh instance for each request. You can do it using javax.inject.Provider interface.
So I've been following the Spring documentation, specifically this part,
http://static.springsource.org/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-collaborators on Dependency Injection, but whenever my code runs, I get an error about bean creation.
Here is portion of my code that I tried to base off the ExampleBean example,
public class TimeFeedHandler implements MessageListener {
String msgID = null;
TimeBayeuxService timeBayeuxService;
public void setTimeBayeuxService(TimeBayeuxService timeBayeuxService) {
this.timeBayeuxService = timeBayeuxService;
}
And my Spring XML file looks like this,
<!-- A POJO that implements the JMS message listener -->
<bean id="timeFeedHandler" class="com.example.streaming.time.TimeFeedHandler" >
<property name="timeBayeuxService" ref="timeBayeuxService"> </property>
</bean>
The error I get is,
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'timeFeedHandler' defined in URL....
Any ideas why or what I'm doing wrong?
Edit, here is the TimeBayeuxService bean,
<!-- Time BayeuxServices -->
<bean id="timeBayeuxService" class="com.example.streaming.time.TimeBayeuxService" lazy-init="true">
<constructor-arg><ref bean="common.bayeux" /></constructor-arg>
<property name="timeBean" ref="time.time" />
</bean>
Here is more of the error. The full error log from STS is wayyyyy too long. I feel like I'm not referencing the TimeBayeuxService bean properly but logically I can't seem to see what I'm doing wrong.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'timeFeedHandler' defined in URL [file:/Users/nullpoint/applicationContext.xml]: Cannot resolve reference to bean 'timeBayeuxService' while setting bean property 'timeFeedHandler'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'timeBayeuxService' defined in URL [file:/Users/nullpoint/applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.example.streaming.time.TimeBayeuxService]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
Here is a portion of the TimeBayeuxService class
public class TimeBayeuxService {
private Bayeux bayeux;
private static StreamingTimeLogGatherer logGatherer;
String testMsgTS = "This is a test message from the original service";
public TimeBayeuxService(Bayeux bayeux) extends SomeBayeuxService{
super(bayeux, TimeBayeuxService.class.getName());
this.bayeux = bayeux;
final Bayeux fbayeux = bayeux;
this.logGatherer = logGatherer;
LogServlet.addLogGatherer(logGatherer);
startThread(fbayeux, testMsgTS, true);
}
timeFeedHandler has a dependency on timeBayeuxService. It can't initialize timeBayeuxService due to NullPointerException so spring can't inject the bean.
According to the error message the NullPointerException happened in the constructor of com.example.streaming.time.TimeBayeuxService. How are you creating common.bayeux bean? Please paste the constructor code for TimeBayeuxService class. Is it an interface? Then you should put the implementation class in the bean definition.
The possible places for NPE. Without the complete stack trace I have to guess the following lines of code:
It can happen inside the constructor of the super class.
These 2 methods: LogServlet.addLogGatherer(logGatherer); startThread(fbayeux, testMsgTS, true);