Java Spring Integration Mail - IllegalArgumentException: 'taskScheduler' must not be null - java

I have some problems converting Imap Idle XML configuration (which works well) to Java Config (which does not work).
I'm pretty new with Spring, so the problem is probably trivial.
Thanks for your help!
XML Configuration:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/mail http://www.springframework.org/schema/integration/mail/spring-integration-mail.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-mail="http://www.springframework.org/schema/integration/mail"
xmlns:util="http://www.springframework.org/schema/util">
<int:channel id="emails"/>
<util:properties id="javaMailProperties">
<prop key="mail.imap.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
<prop key="mail.imap.socketFactory.fallback">false</prop>
<prop key="mail.store.protocol">imaps</prop>
<prop key="mail.debug">true</prop>
</util:properties>
<int-mail:imap-idle-channel-adapter id="mailAdapter"
store-uri="imaps://login:pass#imap-server:993/INBOX"
java-mail-properties="javaMailProperties"
channel="emails"
should-delete-messages="false"
should-mark-messages-as-read="true">
</int-mail:imap-idle-channel-adapter>
</beans>
Java Config:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mail.ImapIdleChannelAdapter;
import org.springframework.integration.mail.ImapMailReceiver;
import org.springframework.messaging.MessageChannel;
import java.util.Properties;
#Configuration
public class ImapConfig{
private Properties javaMailProperties() {
Properties javaMailProperties = new Properties();
javaMailProperties.setProperty("mail.imap.socketFactory.class","javax.net.ssl.SSLSocketFactory");
javaMailProperties.setProperty("mail.imap.socketFactory.fallback","false");
javaMailProperties.setProperty("mail.store.protocol","imaps");
javaMailProperties.setProperty("mail.debug","true");
return javaMailProperties;
}
#Bean
MessageChannel messageChannel() {
return new DirectChannel();
}
#Bean
ImapIdleChannelAdapter mailAdapter() {
ImapMailReceiver mailReceiver = new ImapMailReceiver("imaps://login:pass#imap-server:993/INBOX");
mailReceiver.setJavaMailProperties(javaMailProperties());
mailReceiver.setShouldDeleteMessages(false);
mailReceiver.setShouldMarkMessagesAsRead(true);
ImapIdleChannelAdapter imapIdleChannelAdapter = new ImapIdleChannelAdapter(mailReceiver);
imapIdleChannelAdapter.setOutputChannel(messageChannel());
return imapIdleChannelAdapter;
}
}
Main.java:
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
public class Main {
public static void main(String args[]) {
ApplicationContext ac = new AnnotationConfigApplicationContext(ImapConfig.class);
DirectChannel inputChannel = ac.getBean("messageChannel", DirectChannel.class);
inputChannel.subscribe(new MessageHandler() {
public void handleMessage(Message<?> message) throws MessagingException {
System.out.println(message);
}
});
}
}
Exceptions:
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Failed to start bean 'mailAdapter'; nested exception is java.lang.IllegalArgumentException: 'taskScheduler' must not be null
Exception in thread "main" org.springframework.context.ApplicationContextException: Failed to start bean 'mailAdapter'; nested exception is java.lang.IllegalArgumentException: 'taskScheduler' must not be null
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:176)
at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:51)
at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:346)
at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:149)
at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:112)
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:874)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:544)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:84)
at Main.main(Main.java:13)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.IllegalArgumentException: 'taskScheduler' must not be null
at org.springframework.util.Assert.notNull(Assert.java:115)
at org.springframework.integration.mail.ImapIdleChannelAdapter.doStart(ImapIdleChannelAdapter.java:158)
at org.springframework.integration.endpoint.AbstractEndpoint.start(AbstractEndpoint.java:94)
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:173)
... 13 more
Process finished with exit code 1

You have missed #EnableIntegration on your #Configuration: http://docs.spring.io/spring-integration/docs/4.3.1.RELEASE/reference/html/overview.html#configuration-enable-integration

Related

Cron expression must consist of 6 fields(found 1 in "${cron.expression}) partially fixed but having issues with AnnotationConfigApplicationContext

I am trying to parameterize cron expression and reading it from properties file. During this process I get following exception "Error creating bean with name 'springScheduleCronExample': Initialization of bean failed; nested exception is java.lang.IllegalStateException: Encountered invalid #Scheduled method 'cronJob': Cron expression must consist of 6 fields (found 1 in "${cron.expression}")".
Then I found following post
Using that I cron expression is being read, only if I have
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
SpringScheduleCronExample.class);
define in my main method. The issue that I am having is, I want to run this on server without main method, can anyone please help me with this.
Here is my applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<task:annotation-driven />
<util:properties id="applicationProps" location="application.properties" />
<context:property-placeholder properties-ref="applicationProps" />
<bean class="com.hemal.spring.SpringScheduleCronExample" />
</beans>
My SpringScheduleCronExample.java looks like this
package com.hemal.spring;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
#Configuration
#EnableScheduling
#PropertySource("classpath:application.properties")
public class SpringScheduleCronExample {
private AtomicInteger counter = new AtomicInteger(0);
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
#Scheduled(cron = "${cron.expression}")
public void cronJob() {
int jobId = counter.incrementAndGet();
System.out.println("Job # cron " + new Date() + ", jobId: " + jobId);
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
SpringScheduleCronExample.class);
try {
Thread.sleep(24000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
context.close();
}
}
}
My application Properties has
cron.expression=*/5 * * * * ?
Here is how I got it to work
Application-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<context:property-placeholder properties-ref="applicationProps" />
<context:annotation-config/>
<context:component-scan base-package="com.hemal.spring" />
<task:annotation-driven />
</beans>
MyApplicationConfig.java
package com.hemal.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableScheduling;
#Configuration
#EnableScheduling
#ComponentScan(basePackages = {"com.hemal.spring"})
#PropertySource("classpath:application.properties")
public class MyApplicationConfig {
#Bean
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer properties = new PropertySourcesPlaceholderConfigurer();
properties.setLocation(new ClassPathResource( "application.properties" ));
properties.setIgnoreResourceNotFound(false);
return properties;
}
}
MyApplicationContext.java
package com.hemal.spring;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
public class MyApplicationContext implements WebApplicationInitializer{
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(MyApplicationConfig.class);
servletContext.addListener(new ContextLoaderListener(rootContext));
}
}
My scheduler class
package com.hemal.spring;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
public class SpringScheduleCronExample {
private AtomicInteger counter = new AtomicInteger(0);
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
#Scheduled(cron = "${cron.expression}")
public void cronJob() {
int jobId = counter.incrementAndGet();
System.out.println("Job # cron " + new Date() + ", jobId: " + jobId);
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
SpringScheduleCronExample.class);
try {
Thread.sleep(24000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
context.close();
}
}
}
application.properties
cron.expression=0/5 * * * * ?

declaration can be found for element 'context:property-placeholder'. Spring 4

I browsed around 30 webpages and 50 articles about this and it's still not working.
Here is my code its really simple I'm only a Spring beginner.
App.java
package com.procus.spring.simple.simple;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
*
* #author procus
*/
public class App {
public static void main(String[] args) {
ApplicationContext con = new ClassPathXmlApplicationContext("SpringBeans.xml");
SampleSimpleApplication sam = (SampleSimpleApplication) con.getBean("sam");
sam.run(args);
}
}
SampleSimpleApplication.java
package com.procus.spring.simple.simple;
import com.procus.calculator.basic.BasicCalculator;
import com.procus.spring.simple.simple.service.HelloWorldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#EnableAutoConfiguration
#ComponentScan(basePackageClasses = BasicCalculator.class)
public class SampleSimpleApplication implements CommandLineRunner {
// intentional error
#Autowired
BasicCalculator calculator;
// Simple example shows how a command line spring application can execute an
// injected bean service. Also demonstrates how you can use #Value to inject
// command line args ('--name=whatever') or application properties
#Autowired
private HelloWorldService helloWorldService;
public SampleSimpleApplication() {
}
#Override
public void run(String... args) {
System.out.println(this.helloWorldService.getHelloMessage());
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleSimpleApplication.class, args);
}
}
HelloWorldService.java
package com.procus.spring.simple.simple.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.stereotype.Component;
#Component
#Configuration
#PropertySource(value = { "classpath:application.properties" })
public class HelloWorldService {
#Value("${app.name:World}")
private String name;
public String getHelloMessage() {
return "Hello " + this.name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
SpringBeans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<context:property-placeholder location="classpath*:application.properties"/>
<bean id="DBProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<value>classpath*:application.properties</value>
</property>
</bean>
<bean id="sam" class="com.procus.spring.simple.simple.SampleSimpleApplication"/>
<bean id="serv" class="com.procus.spring.simple.simple.service.HelloWorldService">
<property name="name" value="Jano" />
</bean>
<bean id="calc" class="com.procus.calculator.basic.BasicCalculator">
<constructor-arg value="1.0"/>
</bean>
</beans>
And in resources folder is my application.properties file which contains only app.name=Phil
Exception in thread "main"
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException:
Line 12 in XML document from class path resource [SpringBeans.xml] is
invalid; nested exception is org.xml.sax.SAXParseException;
lineNumber: 12; columnNumber: 81; cvc-complex-type.2.4.c: The matching
wildcard is strict, but no declaration can be found for element
'context:property-placeholder'.
I really tried most of solutions which I found at stackoverflow and few other forums. I`m really new in spring and I will appreciate any help.
In your springbeans.xml you've specified the location as "classpath*:application.properties" classpath with a * whereas in your HelloWorldService.java you've specified the location as "classpath:application.properties". There is a discrepancy in the two locations.
Besides the problem lies in the SpringBeans.xml schema declaration. It is incorrect & incomplete.
After the context declaration http://www.springframework.org/schema/context/spring-context-4.0.xsd is missing
check this this & this
Ideally it should be
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
I am unable to comment -
What i see is you are writing : <context:property-placeholder location="classpath*:application.properties"/>
Why is there a * after classpath.
It should work with - <context:property-placeholder location="classpath:application.properties"/>
Else -
You can use -
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:application.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>
In you Heloworld bean
<bean id="helloworld" class ="package.HelloWorldService" >
<property name="name" value="${app.name}" />
</bean>

Spring with Neo4j - annotation configuration

I try to set up my new project using Spring with Neo4j.
Here is my MainAppConfiguration.java:
package com.nutrilizer.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import com.nutrilizer.app.TestClass;
#Configuration
#PropertySource(value="classpath:/properties/database.properties")
public class MainAppConfig {
#Autowired Environment env;
#Bean
public TestClass testClass() {
return new TestClass(env.getProperty("db.location"));
}
}
Neo4jConfig.java
package com.nutrilizer.configuration;
//imports here
#Configuration
#EnableNeo4jRepositories(basePackages="com.nutrilizer.repository")
public class Neo4jConfig extends Neo4jConfiguration {
#Autowired Environment env;
#Autowired GraphDatabase graphDatabase;
#Bean
public GraphDatabaseService graphDatabaseService() {
return new GraphDatabaseFactory().newEmbeddedDatabase(env.getProperty("db.location"));
}
#Bean
public Neo4jTemplate neo4jTemplate() {
return new Neo4jTemplate(graphDatabaseService());
}
#Bean
public GraphRepositoryFactory graphRepositoryFactory() {
return new GraphRepositoryFactory(neo4jTemplate(), neo4jMappingContext());
}
#Bean
public Neo4jMappingContext neo4jMappingContext() {
return new Neo4jMappingContext();
}
}
configuration.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/data/neo4j
http://www.springframework.org/schema/data/neo4j/spring-neo4j.xsd">
<context:component-scan base-package="com.nutrilizer.configuration" />
<context:annotation-config/>
</beans>
When I try to run this code I get message:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'neo4jConfig' defined in file [/home/mateusz-b/workspace/nutrilizer/target/classes/com/nutrilizer/configuration/Neo4jConfig.class]: Post-processing failed of bean type [class com.nutrilizer.configuration.Neo4jConfig$$EnhancerBySpringCGLIB$$8d313133] failed; nested exception is java.lang.IllegalStateException: Failed to introspect bean class [com.nutrilizer.configuration.Neo4jConfig$$EnhancerBySpringCGLIB$$8d313133] for resource metadata: could not find class that it depends on
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(AbstractAutowireCapableBeanFactory.java:928)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:512)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.nutrilizer.app.MainApp.main(MainApp.java:10)
Caused by: java.lang.IllegalStateException: Failed to introspect bean class [com.nutrilizer.configuration.Neo4jConfig$$EnhancerBySpringCGLIB$$8d313133] for resource metadata: could not find class that it depends on
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.findResourceMetadata(CommonAnnotationBeanPostProcessor.java:331)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(CommonAnnotationBeanPostProcessor.java:284)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(AbstractAutowireCapableBeanFactory.java:923)
... 12 more
Caused by: java.lang.NoClassDefFoundError: Ljavax/validation/Validator;
at java.lang.Class.getDeclaredFields0(Native Method)
at java.lang.Class.privateGetDeclaredFields(Class.java:2499)
at java.lang.Class.getDeclaredFields(Class.java:1811)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.buildResourceMetadata(CommonAnnotationBeanPostProcessor.java:346)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.findResourceMetadata(CommonAnnotationBeanPostProcessor.java:327)
... 14 more
Caused by: java.lang.ClassNotFoundException: javax.validation.Validator
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 19 more
I don't have any idea why it doesn't work. Can you tell me what's wrong with this configuration? Have you any solutions?

Service Class not being instantiated during #Autowire call

I am attempting to use a #Service class in my messaging application, however the class is not instantiated via #Autowire when I try from a generic class. It is only instantiated when I use the Controller.
Here is my controller:
package hello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import hello.Application;
#Controller
public class HelloController {
#Autowired
private MessageSender sender;
#RequestMapping(value="/", method=RequestMethod.GET)
public String index() {
return "index";
}
#MessageMapping("/hello")
#SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
System.out.println("Sending message...");
beginRoute(message.getName());
sender.greet("thunder");
return new Greeting("Hello, " + message.getName() + "!");
}
public void beginRoute(String message) {
Application.startBody(message);
}
}
The above call to sender.greet is successful.
Here is the other class I attempt to use the service in:
package com.routing.integration;
import hello.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;
#Component
public class modifier {
#Autowired
private MessageSender sender;
public boolean adder(String words) throws Exception {
sender.greet(words);
}
}
When I attempt to call sender.greet as above, I get a NullPointerException and when debugging, I find that sender is null at the time of the call to sender.greet. Is the service class not instantiating in modifier?
Finally, here is the MessageSender service class:
#Service
public class MessageSender {
#Autowired
private SimpMessagingTemplate template;
#RequestMapping(value="/hello", method=RequestMethod.POST)
public void greet(String greeting) {
Greeting text = new Greeting("Goodbye, " + greeting + "!");
this.template.convertAndSend("/topic/greetings", text);
}
}
How can I ensure that #Autowire instantiates the MessageSender in every class?
EDIT
Here is where the call to modifier is made. It is made from a camel route:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:camel="http://camel.apache.org/schema/spring"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:core="http://activemq.apache.org/schema/core"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://camel.apache.org/schema/osgi http://camel.apache.org/schema/osgi/camel-osgi.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core">
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="activemq:queue:testQSource"/>
<choice>
<when>
<method ref="securityBean"/>
<log message="Routing message from testQSource to testQDestination queue with data ${body}"/>
<to uri="activemq:queue:testQDestination"/>
<to uri="activationBean"/>
<to uri="accountVerificationBean"/>
<to uri="billingCheckingBean"/>
<to uri="deviceConnectorBean"/>
<to uri="deviceActivatorBean"/>
<log message="Account activated: ${body}"/>
</when>
<otherwise>
<log message="message went to stomp: ${body}"/>
</otherwise>
</choice>
</route>
</camelContext>
<camel:camelContext id="camel-client">
<camel:template id="camelTemplate" />
</camel:camelContext>
<bean id="activemq" class="org.apache.activemq.camel.component.ActiveMQComponent">
<property name="brokerURL" value="tcp://localhost:61616" />
</bean>
<bean id="browserBean" class="hello.HelloController"/>
<bean id="securityBean" class="com.routing.integration.modifier"/>
<bean id="activationBean" class="com.routing.integration.ActionApp"/>
<bean id="accountVerificationBean" class="com.routing.integration.AccountVerifier"/>
<bean id="billingCheckingBean" class="com.routing.integration.BillingChecker"/>
<bean id="deviceConnectorBean" class="com.routing.integration.DeviceConnector"/>
<bean id="deviceActivatorBean" class="com.routing.integration.DeviceActivator"/>
</beans>
Here is the stacktrace:
Stacktrace
--------------------------------------------------------------------------------------- ------------------------------------------------
java.lang.NullPointerException
at com.routing.integration.modifier.adder(modifier.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.camel.component.bean.MethodInfo.invoke(MethodInfo.java:407)
at org.apache.camel.component.bean.MethodInfo$1.doProceed(MethodInfo.java:278)
at org.apache.camel.component.bean.MethodInfo$1.proceed(MethodInfo.java:251)
at org.apache.camel.component.bean.BeanProcessor.process(BeanProcessor.java:166)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:105)
at org.apache.camel.component.bean.BeanProcessor.process(BeanProcessor.java:67)
at org.apache.camel.language.bean.BeanExpression$InvokeProcessor.process(BeanExpression.java:1 89)
at org.apache.camel.language.bean.BeanExpression.evaluate(BeanExpression.java:123)
at org.apache.camel.language.bean.BeanExpression.matches(BeanExpression.java:137)
at org.apache.camel.processor.ChoiceProcessor.process(ChoiceProcessor.java:90)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java: 72)
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:398)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:105)
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:87)
at org.apache.camel.component.jms.EndpointMessageListener.onMessage(EndpointMessageListener.ja va:103)
at org.springframework.jms.listener.AbstractMessageListenerContainer.doInvokeListener(Abstract MessageListenerContainer.java:562)
at org.springframework.jms.listener.AbstractMessageListenerContainer.invokeListener(AbstractMe ssageListenerContainer.java:500)
at org.springframework.jms.listener.AbstractMessageListenerContainer.doExecuteListener(Abstrac tMessageListenerContainer.java:468)
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.doReceiveAndExecut e(AbstractPollingMessageListenerContainer.java:325)
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.receiveAndExecute( AbstractPollingMessageListenerContainer.java:263)
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoke r.invokeListener(DefaultMessageListenerContainer.java:1102)
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoke r.executeOngoingLoop(DefaultMessageListenerContainer.java:1094)
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoke r.run(DefaultMessageListenerContainer.java:991)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
WARN : org.apache.camel.component.jms.EndpointMessageListener - Execution of JMS message listener failed. Caused by: [org.apache.camel.RuntimeCamelException - java.lang.NullPointerException]
org.apache.camel.RuntimeCamelException: java.lang.NullPointerException
at org.apache.camel.util.ObjectHelper.wrapRuntimeCamelException(ObjectHelper.java:1363)
at org.apache.camel.component.jms.EndpointMessageListener$EndpointMessageListenerAsyncCallback .done(EndpointMessageListener.java:186)
at org.apache.camel.component.jms.EndpointMessageListener.onMessage(EndpointMessageListener.ja va:107)
at org.springframework.jms.listener.AbstractMessageListenerContainer.doInvokeListener(Abstract MessageListenerContainer.java:562)
at org.springframework.jms.listener.AbstractMessageListenerContainer.invokeListener(AbstractMe ssageListenerContainer.java:500)
at org.springframework.jms.listener.AbstractMessageListenerContainer.doExecuteListener(Abstrac tMessageListenerContainer.java:468)
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.doReceiveAndExecut e(AbstractPollingMessageListenerContainer.java:325)
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.receiveAndExecute( AbstractPollingMessageListenerContainer.java:263)
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoke r.invokeListener(DefaultMessageListenerContainer.java:1102)
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoke r.executeOngoingLoop(DefaultMessageListenerContainer.java:1094)
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoke r.run(DefaultMessageListenerContainer.java:991)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at com.routing.integration.modifier.adder(modifier.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.camel.component.bean.MethodInfo.invoke(MethodInfo.java:407)
at org.apache.camel.component.bean.MethodInfo$1.doProceed(MethodInfo.java:278)
at org.apache.camel.component.bean.MethodInfo$1.proceed(MethodInfo.java:251)
at org.apache.camel.component.bean.BeanProcessor.process(BeanProcessor.java:166)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:105)
at org.apache.camel.component.bean.BeanProcessor.process(BeanProcessor.java:67)
at org.apache.camel.language.bean.BeanExpression$InvokeProcessor.process(BeanExpression.java:1 89)
at org.apache.camel.language.bean.BeanExpression.evaluate(BeanExpression.java:123)
at org.apache.camel.language.bean.BeanExpression.matches(BeanExpression.java:137)
at org.apache.camel.processor.ChoiceProcessor.process(ChoiceProcessor.java:90)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java: 72)
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:398)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:105)
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:87)
at org.apache.camel.component.jms.EndpointMessageListener.onMessage(EndpointMessageListener.ja va:103)
... 11 more
EDIT 2
Here is my main class that calls ComponentScan:
package hello;
import org.apache.camel.ProducerTemplate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ClassPathXmlApplicationContext;
#Configuration
#EnableAutoConfiguration
#ComponentScan(basePackages = {"hello", "com.routing.integration"})
public class Application {
static ApplicationContext context = null;
static ProducerTemplate camelTemplate = null;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
System.out.println("----------------------\nSpringBootComplete\n----------------------");
startBody("startup");
}
public static void startBody(String message) {
if (context == null) {
context = new ClassPathXmlApplicationContext("camelspring.xml");
camelTemplate = context.getBean("camelTemplate", ProducerTemplate.class);
}
if (message != "startup"){
camelTemplate.sendBody("activemq:queue:testQSource", message);
}
}
}
Your Application class should look like this:
#Configuration
#ComponentScan(basePackages = {"hello", "com.routing.integration"})
#EnableAutoConfiguration
#ImportResource("classpath:camel.xml")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Where camel.xml is the xml configuration file that contains your camel definitions.
If you need any of the beans defined in the xml configuration, like camelTemplate in your xml, you can get a reference of it like this, for example:
package hello;
import javax.annotation.Resource;
import org.apache.camel.ProducerTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class MyController {
#Resource(name="camelTemplate")
private ProducerTemplate template;
#RequestMapping("/")
String home() {
System.out.println(template);
return "Hello World!";
}
}
As I said in the comments, don't create an app context manually. Register the beans you want with #Component, #Service, #Configuration and #Bean etc. If you need xml configuration that is difficult to reproduce in Java code, use #ImportResource.
In the xml config file you have, you can replace browserBean bean with a #Controller annotation placed on the hello.HelloController class.
Your activemq bean could translate to something like this in Java Config:
#Configuration
public class Config {
#Bean
public ActiveMQComponent activemq() {
ActiveMQComponent comp = new ActiveMQComponent();
comp.setBrokerUrl("tcp://localhost:61616");
return comp;
}
}

java spring aop: java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut LoginMethod

I 've designed a db application, but need to handle the exception connecting to db using spring aop, classes i 've are shown below
LoginInterface.java
LoginInterface(){
ApplicationContext context = new ClassPathXmlApplicationContext("LoginApp.xml");
Login login = (Login) context.getBean("Login");
login.loginMethod(username,password);
}
Login.java
{
loginMethod(String username, char[] pwd) throws ClassNOtFoundException, SQLException{
...
}
}
LoginProfiler.java
package dbapp;
import java.sql.SQLException;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.JoinPoint;
#Aspect
public class LoginProfiler {
#Pointcut("execution(* dbapp.Login.loginMethod(String, char[])throws java.lang.ClassNotFoundException, java.sql.SQLException)")
public void loginMethod(){}
#Around("loginMethod()")
public void handleException(final ProceedingJoinPoint pJoinPoint )throws Throwable{
try{
pJoinPoint.proceed();
}catch(Exception e) {
if((e.getCause().toString()).contains("UnknownHostException") ){
System.out.println("Unknown Host ");
}else if((e.getCause().toString()).contains("ConnectException")){
System.out.println("Connection Problem ");
}
}
}
}
LoginApp.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"
default-destroy-method="destroy"
default-init-method="afterPropertiesSet"
default-autowire="byName">
<!-- Enable the #AspectJ support -->
<aop:aspectj-autoproxy />
<bean id="LoginProfiler" class="dbapp.LoginProfiler" />
<bean id="Login" class="dbapp.Login" />
</beans>
I've got the following Exception
Erg.springframework.beans.factory.BeanCreationException: Error creating bean with name 'Login' defined in class path resource [LoginApp.xml]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut LoginMethod
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480)
at
..
Caused by: java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut LoginMethod
at org.aspectj.weaver.tools.PointcutParser.parsePointcutExpression(PointcutParser.java:315)
at org.springframework.aop.aspectj.AspectJExpressionPointcut.buildPointcutExpression(AspectJExpressionPointcut.java:206)
at
Try this.
#Aspect
public class LoginProfiler {
#Pointcut("execution(* dbapp.Login.loginMethod(String, char[])throws java.lang.ClassNotFoundException, java.sql.SQLException)")
public void loginMethod(){}
#AfterThrowing("loginMethod()")
public void handleException(final JoinPoint joinPoint){
System.out.println("Am able to Handle");
}
}
or
#Aspect
public class LoginProfiler {
#AfterThrowing("execution(* dbapp.Login.loginMethod(String, char[])throws java.lang.ClassNotFoundException, java.sql.SQLException)")
public void handleException(final JoinPoint joinPoint){
System.out.println("Am able to Handle");
}
}
Also it would be better if you spend some time learning about spring-aop. From your question it looks like you really don't understand AOP. You are trying to cut and paste from some sample code.

Categories