I am converting a project done using spring jms into spring boot project. I dont know how to convert the context.xml in spring jms into the configuration class in spring boot. My context.xml is as follows
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>file:./config-env-receiver.properties</value>
</property>
</bean>
<bean id="stepConnectionFactory" class="com.ibm.mq.jms.MQQueueConnectionFactory">
<property name="hostName">
<value>${mq.hostname.step}</value>
</property>
<property name="port">
<value>${mq.port.step}</value>
</property>
<property name="channel">
<value>${mq.channel.step}</value>
</property>
<property name="queueManager">
<value>${mq.queuemanager.step}</value>
</property>
<property name="transportType">
<value>1</value>
</property>
</bean>
<bean id="jmsDestination" class="com.ibm.mq.jms.MQQueue">
<constructor-arg value="${mq.queuename.step}" />
</bean>
<bean
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="stepConnectionFactory" />
<property name="sessionTransacted" value="true" />
<property name="destinationName" value="${mq.queuename.step}" />
<property name="exceptionListener" ref="exceptionListener" />
<property name="messageListener" ref="stepOutListenerItemCreateUpdate" />
</bean>
<bean id="exceptionListener" class="com.message.view.CustomException">
</bean>
<bean id="stepOutListenerItemCreateUpdate"
class="com.message.view.WMQueueMessageConsumer">
</bean>
<bean id="springConnectionFactory"
class="org.springframework.jms.connection.SingleConnectionFactory">
<property name="targetConnectionFactory" ref="stepConnectionFactory" />
</bean>
<bean id="jmsTemplateStep" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="springConnectionFactory" />
<property name="defaultDestination" ref="jmsDestination" />
</bean>
<context:component-scan base-package="com.message.view">
</context:component-scan>
I tried creating the Application.class as follows.
package hello;
import java.util.Arrays;
import javax.jms.JMSException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ImportResource;
import org.springframework.jms.connection.SingleConnectionFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
import com.ibm.mq.jms.MQQueue;
import com.ibm.mq.jms.MQQueueConnectionFactory;
#SpringBootApplication
//#ImportResource("classpath:context_receiver.xml")
public class Application {
#Autowired
public CustomException customException;
#Autowired
public MessageListener messageListener;
#Bean
public MQQueueConnectionFactory getMQconnectionfactory(){
MQQueueConnectionFactory mqconfactory=new MQQueueConnectionFactory();
try {
mqconfactory.setHostName("*******");
mqconfactory.setPort(*****);
mqconfactory.setChannel("**********");
mqconfactory.setQueueManager("********");
mqconfactory.setTransportType(1);
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mqconfactory;
}
#Bean
public MQQueue getMQQueue(){
return new MQQueue();
}
#Bean
public DefaultMessageListenerContainer getDefaultMessageListenerContainer(){
DefaultMessageListenerContainer defmesliscont=new DefaultMessageListenerContainer();
defmesliscont.setConnectionFactory(getMQconnectionfactory());
defmesliscont.setSessionTransacted(true);
defmesliscont.setDestinationName("********");
defmesliscont.setExceptionListener(customException);
defmesliscont.setMessageListener(messageListener);
return defmesliscont;
}
#Bean
public SingleConnectionFactory getSingleConnectionFactory(){
SingleConnectionFactory singleConnectionFactory=new SingleConnectionFactory();
singleConnectionFactory.setTargetConnectionFactory(getMQconnectionfactory());
return singleConnectionFactory;
}
#Bean
public JmsTemplate getJmsTemplate(){
JmsTemplate jmsTemplate=new JmsTemplate();
jmsTemplate.setConnectionFactory(getSingleConnectionFactory());
jmsTemplate.setDefaultDestination(getMQQueue());
return jmsTemplate;
}
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
}
}
But am getting this error.
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: ; nested exception is java.lang.IllegalArgumentException: Attribute 'exclude' is of type [Class[]], but [String[]] was expected. Cause:
at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:383)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:162)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:296)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:240)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:254)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:94)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:609)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
at hello.Application.main(Application.java:81)
Caused by: java.lang.IllegalArgumentException: Attribute 'exclude' is of type [Class[]], but [String[]] was expected. Cause:
at org.springframework.core.annotation.AnnotationAttributes.doGet(AnnotationAttributes.java:117)
at org.springframework.core.annotation.AnnotationAttributes.getStringArray(AnnotationAttributes.java:70)
at org.springframework.boot.autoconfigure.EnableAutoConfigurationImportSelector.selectImports(EnableAutoConfigurationImportSelector.java:69)
at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:379)
... 13 common frames omitted
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: ; nested exception is java.lang.IllegalArgumentException: Attribute 'exclude' is of type [Class[]], but [String[]] was expected. Cause:
at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:383)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:162)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:296)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:240)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:254)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:94)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:609)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
at hello.Application.main(Application.java:81)
Caused by: java.lang.IllegalArgumentException: Attribute 'exclude' is of type [Class[]], but [String[]] was expected. Cause:
at org.springframework.core.annotation.AnnotationAttributes.doGet(AnnotationAttributes.java:117)
at org.springframework.core.annotation.AnnotationAttributes.getStringArray(AnnotationAttributes.java:70)
at org.springframework.boot.autoconfigure.EnableAutoConfigurationImportSelector.selectImports(EnableAutoConfigurationImportSelector.java:69)
at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:379)
... 13 more
I have even tried importing the context.xml using #ImportResource. But that too is not working. Though i prefer configuring it through the Application.class.
Please tell me what am doing wrong. Thanks.
I've got it working. Here is the snippet from thre working pom file
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
</dependency>
Upgrade you spring version to 4.1.5.RELEASE
I've got the same issue.
Looks like the problem is in incompatibility of EnableAutoConfiguration which is part of SpringBootApplication and https://github.com/spring-projects/spring-framework/blob/master/spring-core/src/main/java/org/springframework/core/annotation/AnnotationAttributes.java. EnableAutoConfiguration has exclude as Class [], but AnnotationAttributes expects String []. Most likely the versions are incompatible. I did not come up with solution yet though.
close idea
regenerate idea configuration files
$ mvn idea:clean
$ mvn idea:idea
reimport projects
run again in the idea
Related
I am trying to run this test on Arquillian:
#ExtendWith(ArquillianExtension.class)
class ArquillianTest {
#Deployment
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, "arquillian-test.war");
}
#Test
void execTest() {
fail("Always fails");
}
}
but it gets ignored and the whole execution just fails with:
INFO: JBoss Threads version 3.1.0.Final
Test ignored.
java.lang.NoClassDefFoundError: org/jboss/threads/AsyncFuture
at org.jboss.as.controller.client.ModelControllerClient$Factory.create(ModelControllerClient.java:609)
at org.jboss.as.arquillian.container.CommonDeployableContainer.start(CommonDeployableContainer.java:121)
at org.jboss.arquillian.container.impl.ContainerImpl.start(ContainerImpl.java:179)
I do not think I am missing anything in my deployment method, since there are no classes involved in this simple test, but I am new to Arquillian.
I found a bug report of the same error, but it was in 2014 and apparently resolved: https://lists.jboss.org/pipermail/jboss-jira/2014-April/256446.html
This is my pom.xml (relevant parts):
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
</plugin>
<dependency>
<groupId>org.jboss.arquillian</groupId>
<artifactId>arquillian-bom</artifactId>
<version>1.7.0.Alpha10</version>
<type>pom</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.junit5</groupId>
<artifactId>arquillian-junit5-container</artifactId>
<version>1.7.0.Alpha10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.protocol</groupId>
<artifactId>arquillian-protocol-servlet-jakarta</artifactId>
<version>1.7.0.Alpha10</version>
</dependency>
<dependency>
<groupId>org.wildfly.arquillian</groupId>
<artifactId>wildfly-arquillian-container-managed</artifactId>
<version>5.0.0.Alpha2</version>
<scope>test</scope>
</dependency>
and this is my arquillian.xml:
<arquillian
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://jboss.org/schema/arquillian"
xsi:schemaLocation="http://jboss.org/schema/arquillian
http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
<defaultProtocol type="Servlet 5.0"/>
<container qualifier="wildfly" default="true">
<configuration>
<property name="jbossHome">C:\Users\sotan\Software\wildfly-preview-25.0.1.Final</property>
<property name="javaVmArguments">-Djboss.socket.binding.port-offset=100</property>
<property name="managementPort">10090</property>
</configuration>
</container>
</arquillian>
I'm creating a REST Service with Apache Camel and CXF-RS, using the following tutorial: https://www.javainuse.com/camel/apache_camel_rest_cxfrs
I've set up the code as shown in the tutorial and followed the steps correctly. After building the Maven project, I have successfully been able to install the bundle on Apache Karaf, using the SNAPSHOT file created. (A new Bundle ID was created).
When I run the command to 'start' the newly created bundle, it seemingly works with no errors being shown. However, when I access http://localhost:8181/cxf as mentioned towards the end of the tutorial, it says 'No services have been found':
Can you please advise me on what could be causing this problem?
Thank you.
My Project Structure:
My Code:
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.fuseproject</groupId>
<artifactId>camel-cxfrs-core</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>bundle</packaging>
<repositories>
<repository>
<id>Central2</id>
<name>Central2</name>
<url>https://repo.maven.org/maven2</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
<version>2.12.0</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-cxf</artifactId>
<version>2.12.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<version>2.4.0</version>
</plugin>
</plugins>
</build>
</project>
CamelProcessor.java:
package com.fuseproject.beans;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
public class CamelProcessor implements Processor {
public void process(Exchange exchange) throws Exception {
// Get input from exchange
String msg = exchange.getIn().getBody(String.class);
// set output in exchange
exchange.getOut().setBody("Hello World " + msg);
}
}
EmployeeServiceResource.java:
package com.fuseproject.beans;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
#Path("/")
public class EmployeeServiceResource {
public EmployeeServiceResource() {
}
#GET
#Path("/employees/{name}/")
public String getCustomer(#PathParam("name") String name) {
return null;
}
}
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:cxf="http://camel.apache.org/schema/cxf"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/cxf http://camel.apache.org/schema/cxf/camel-cxf.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<cxf:rsServer id="restService" address="http://localhost:9000/employeeservice"
serviceClass="com.fuseproject.beans.EmployeeServiceResource">
</cxf:rsServer>
<bean id="processor" class="com.fuseproject.beans.CamelProcessor" />
<camelContext id="camelId" xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="cxfrs://bean://restService" />
<process ref="processor" />
</route>
</camelContext>
</beans>
I am getting a 404 error when I test my REST Spring WebService in Postman.
Can anyone suggest a solution??
My code :
src/main/resources/spring/application-config.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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Uncomment and add your base-package here:
<context:component-scan
base-package="org.springframework.samples.service"/> -->
</beans>
-------------------------------------------------------------------------------------------------------------------------------------------
src/main/resources/logback.xml
-------------------------------------------------------------------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!-- configuration file for LogBack (slf4J implementation)
See here for more details: http://gordondickens.com/wordpress/2013/03/27/sawing-through-the-java-loggers/ -->
<configuration scan="true" scanPeriod="30 seconds">
<contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
<resetJUL>true</resetJUL>
</contextListener>
<!-- To enable JMX Management -->
<jmxConfigurator/>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%-5level %logger{0} - %msg%n</pattern>
</encoder>
</appender>
<!--<logger name="org.hibernate" level="debug"/> -->
<!-- Uncomment and add your logger here:
<logger name="org.springframework.samples.service.service" level="debug"/> -->
<root level="info">
<appender-ref ref="console"/>
</root>
</configuration>
---------------------------------------------------------------------------------------------------------------------------------------------
src/main/webapp/WEB-INF/mvc-config.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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
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">
<!-- Uncomment and your base-package here:
<context:component-scan
base-package="org.springframework.samples.web"/> -->
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- Example: a logical view name of 'showMessage' is mapped to '/WEB-INF/jsp/showMessage.jsp' -->
<property name="prefix" value="/WEB-INF/view/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
---------------------------------------------------------------------------------------------------------------------------------------------
src/main/webapp/WEB-INF/web.xml
---------------------------------------------------------------------------------------------------------------------------------------------
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>ManageUserRoles</display-name>
<!--
- Location of the XML file that defines the root application context.
- Applied by ContextLoaderListener.
-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/application-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--
- Servlet that dispatches request to registered handlers (Controller implementations).
-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
//////////////////////////Controller///////////////////////////////
package com.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.model.Role;
#Controller
public class RoleController {
private static final Logger logger = LoggerFactory.getLogger(RoleController.class);
Map<String, Role> roleData = new HashMap<String, Role>();
#RequestMapping(value = "/role/{role_name}", method = RequestMethod.GET,headers="Accept=application/json")
public #ResponseBody Role findRole(#PathVariable("role_name") String role_name)
{
logger.info("Get a single role with name="+role_name);
return roleData.get(role_name);
}
#RequestMapping(value = "/roles", method = RequestMethod.GET)
public #ResponseBody List<Role> getAllRoles()
{
logger.info("Start getAllRoles.");
List<Role> list_roles = new ArrayList<Role>();
list_roles = createRoleList();
return list_roles;
}
public List<Role> createRoleList()
{
Role role1 = new Role("NP Sherm Test", "NP Test", "Active");
Role role2 = new Role("Sherm Employee Test", "Employee access test role", "Active");
Role role3 = new Role("Sherm Manager Test", "Manager test user role", "Active");
List<Role> list_roles = new ArrayList<Role>();
list_roles.add(role1);
list_roles.add(role2);
list_roles.add(role3);
return list_roles;
}
#RequestMapping(value="/roles/new/",method=RequestMethod.POST,headers="Accept=application/json")
public #ResponseBody Role addRole(#RequestBody Role role)
{
logger.info("Start Add Role");
Role roleGet = roleData.put(role.getRole_name(), role);
return roleGet;
}
#RequestMapping(value="/roles/new/",method=RequestMethod.PUT,headers="Accept=application/json")
public #ResponseBody Role editRole(#RequestBody Role role)
{
Role role_update = new Role();
role.setRole_name(role.getRole_name());
role.setRole_desc(role.getRole_desc());
role.setRole_status(role.getRole_status());
return role_update;
}
}
/////////////////////////////////////Model///////////////////////////////
package com.model;
public class Role {
private String role_name;
private String role_desc;
private String role_status;
public Role(){}
public Role(String role_name, String role_desc, String role_status) {
super();
this.role_name = role_name;
this.role_desc = role_desc;
this.role_status = role_status;
}
public String getRole_name() {
return role_name;
}
public void setRole_name(String role_name) {
this.role_name = role_name;
}
public String getRole_desc() {
return role_desc;
}
public void setRole_desc(String role_desc) {
this.role_desc = role_desc;
}
public String getRole_status() {
return role_status;
}
public void setRole_status(String role_status) {
this.role_status = role_status;
}
}
//////////////////////////////pom.xml//////////////////////////////////
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.samples.service.service</groupId>
<artifactId>ManageUserRoles</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<!-- Generic properties -->
<java.version>1.6</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- Web -->
<jsp.version>2.2</jsp.version>
<jstl.version>1.2</jstl.version>
<servlet.version>2.5</servlet.version>
<!-- Spring -->
<spring-framework.version>3.2.3.RELEASE</spring-framework.version>
<!-- Hibernate / JPA -->
<hibernate.version>4.2.1.Final</hibernate.version>
<!-- Logging -->
<logback.version>1.0.13</logback.version>
<slf4j.version>1.7.5</slf4j.version>
<!-- Test -->
<junit.version>4.11</junit.version>
</properties>
<dependencies>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Other Web dependencies -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp.version}</version>
<scope>provided</scope>
</dependency>
<!-- Spring and Transactions -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>runtime</scope>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- Test Artifacts -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-framework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
As you don't have any specific application context, the problem is with the current URL mapping i.e., the URI ManageUserRoles did not map to the controller, so change the code as below:
#Controller("ManageUserRoles")
public class RoleController {
// Add all you existing handler methods
}
After your UPDATE 1:
Also, your componentscan is not correct in mvc-config.xml because of which controller can't be detected:
base-package="org.springframework.samples.web" change it to base-package="com.controller"
I am trying to send an email but before I was getting a nullpointerexception error which was due to mailSender not getting set correctly, now I edited the code as it is shown below and I am not getting any exception but the code breaks at the line
MimeMessage message = mailSender.createMimeMessage();
Here is my code (both sendMail() and addNewAlarm() are inside the same class "ElementService"):
public class ElementService implements ApplicationContextAware {
private ApplicationContext ac;
public void sendMail(String toAddress, String subject, String body) throws Exception{
JavaMailSender mailSender = (JavaMailSender) ac.getBean("mailSender");
MimeMessage message = mailSender.createMimeMessage();
try{
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom("xxx#gmail.com");
helper.setTo(toAddress);
helper.setSubject(subject);
helper.setText(body);
}catch (MessagingException e) {
throw new MailParseException(e);
}
try{
mailSender.send(message);
}
catch(Exception e){
throw e;
}
}
//I want an email to be sent every 30 seconds
#Scheduled(fixedDelay = 30*1000)
public void function2RepeatEvery30Seconds()
{
MailService mailer = (MailService) ac.getBean("mailService");
mailer.sendMail("xxx#hotmail.com","subject","body");
//does other stuff..
}
#Override
public void setApplicationContext(ApplicationContext ac) throws BeansException {
this.ac = ac;
}
}
These are the beans in my xml:
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<!-- SMTP settings -->
<property name="host" value="smtp.gmail.com" />
<property name="port" value="587" />
<property name="username" value="***#gmail.com" />
<property name="password" value="*****" />
<property name="javaMailProperties">
<!-- additional properties specific to JavaMail -->
<props>
<prop key="mail.transport.protocol">smtp</prop>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
</props>
</property>
</bean>
In debug mode I can see that mailSender has been set according to the properties shown on the mailSender bean.
I finally did it!! Thanks to Serge Ballesta of course. I should have been using log4j all along... I researched the Exception MessageRemovedIOException and I found this post java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger for JUnit test case for Java mail where there is a suggestion in the comments to change
<dependency> <groupId>javax.mail</groupId> <artifactId>javax.mail-api</artifactId> <version>1.5.2</version> </dependency>
to
<dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.5.2</version> </dependency>
I also had to change this:
<prop key="mail.smtp.starttls.enable">true</prop>
to this:
<prop key="mail.smtp.starttls.enable">false</prop>
Thank you very much for your time and advice #Serge Ballesta!
Ok, obviously the mailSender is null which causes the error. My guess would be that your #Autowired annotation is not processed. Do you have AutowiredAnnotationBeanPostProcessor registered? You can do that for example by using <context:annotation-config /> in your Spring configuration.
Other option (without using #Autowired) is to manually specify the dependency on mailSender in your mailService bean definition like so:
<bean id="mailService" class="gr.mobics.allweb.service.MailService" scope="singleton">
<property name="mailSender" ref="mailSender" />
</bean>
I have not tested this, but it seems like this is the cause of your problem. If these solutions don't work you, leave a comment and I'll try to update the answer.
I'm trying to learn how to make tests with JUnit in Spring. I have written this test:
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.blah.baseProject.database.model.Usuario;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "file:src/test/resources/test-applicationContext.xml" })
public class LoginTest2 {
#Autowired
UsuarioDAO usuario;
private final static Logger logger = Logger.getLogger(LoginTest2.class);
#Test
public void test() {
logger.info("hi "+usuario.findAll());
}
}
But I get this error:
ERROR: org.springframework.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener#54e063d] to prepare test instance [com.blah.baseProject.LoginTest2#457b9183]
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:122)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:105)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:74)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:312)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myDataSource': Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1482)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:608)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:120)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:248)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91)
... 25 more
Caused by: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:307)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:344)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at org.springframework.jndi.JndiTemplate$1.doInContext(JndiTemplate.java:154)
at org.springframework.jndi.JndiTemplate.execute(JndiTemplate.java:87)
at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:152)
at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:178)
at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:95)
at org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:105)
at org.springframework.jndi.JndiObjectFactoryBean.lookupWithFallback(JndiObjectFactoryBean.java:201)
at org.springframework.jndi.JndiObjectFactoryBean.afterPropertiesSet(JndiObjectFactoryBean.java:187)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1541)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1479)
This 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:jee="http://www.springframework.org/schema/jee"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">
<!-- JDBC Data Source -->
<jee:jndi-lookup id="myDataSource" jndi-name="java:comp/env/jdbc/rhcimax"/>
<!-- Hibernate Session Factory -->
<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="packagesToScan">
<array>
<value>com.blah.baseProject</value>
</array>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
</value>
</property>
</bean>
<!-- Hibernate Transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<!-- Activates annotation based transaction management -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:component-scan base-package="com.blah.baseProject">
<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
</beans>
I'm pretty lost with all this, any help will be appreciated.
Edit:
This is my UsuarioDAO:
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.blah.baseProject.database.DAO.UsuarioDAO;
import com.blah.baseProject.database.model.Usuario;
#Repository(value="UsuarioDao")
public class UsuarioHibernateDAO implements UsuarioDAO{
#Autowired
private SessionFactory mySessionFactory;
public void insert(Usuario user) {
mySessionFactory.getCurrentSession().save(user);
}
public void update(Usuario user) {
mySessionFactory.getCurrentSession().update(user);
}
/**
* #Transactional annotation below will trigger Spring Hibernate transaction manager to automatically create
* a hibernate session. See src/main/webapp/servlet-context.xml
*/
#Transactional
public List<Usuario> findAll() {
return mySessionFactory.getCurrentSession().createQuery("from Usuario").list();
}
public Usuario findById(String idUser) {
return (Usuario) mySessionFactory.getCurrentSession().load(Usuario.class, idUser);
}
public void delete(Usuario user) {
mySessionFactory.getCurrentSession().delete(user);
}
}
EDIT2:
//src/main/webapp/WEB-INF/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:jee="http://www.springframework.org/schema/jee"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">
<!-- JDBC Data Source-->
<jee:jndi-lookup id="myDataSource" jndi-name="java:comp/env/jdbc/rhcimax"/>
<!-- Hibernate Session Factory -->
<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="packagesToScan">
<array>
<value>com.blah.baseProject.test</value>
</array>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
</value>
</property>
</bean>
<!-- Hibernate Transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<!-- Activates annotation based transaction management -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:component-scan base-package="com.blah.baseProject.test">
<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
</beans>
//src/main/test/resources/test-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:jee="http://www.springframework.org/schema/jee"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">
<!-- JDBC Data Source. It is assumed you have MySQL running on localhost port 3306 with
username root and blank password. Change below if it's not the case -->
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/rhcimax"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
<property name="validationQuery" value="SELECT 1"/>
</bean>
</beans>
//loginTest2.java
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.blah.baseProject.database.DAO.UsuarioDAO;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/applicationContext.xml", "classpath:test-applicationContext.xml" })
public class LoginTest2 {
#Autowired
UsuarioDAO usuarioDao;
private final static Logger logger = Logger.getLogger(LoginTest2.class);
#Test
public void test() {
logger.info("hi "+usuarioDao.findAll());
}
}
New Exception:
ERROR: org.springframework.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#67beff98] to prepare test instance [com.blah.baseProject.test.LoginTest2#2c7e895e]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.blah.baseProject.test.LoginTest2': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.blah.baseProject.database.DAO.UsuarioDAO com.blah.baseProject.test.LoginTest2.usuarioDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.blah.baseProject.database.DAO.UsuarioDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1116)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:376)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:312)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.blah.baseProject.database.DAO.UsuarioDAO com.blah.baseProject.test.LoginTest2.usuarioDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.blah.baseProject.database.DAO.UsuarioDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
... 26 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.blah.baseProject.database.DAO.UsuarioDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:856)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
... 28 more
INFO : org.springframework.context.support.GenericApplicationContext - Closing org.springframework.context.support.GenericApplicationContext#1f427975: startup date [Thu Aug 22 09:22:47 VET 2013]; root of context hierarchy
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#2af0b852: defining beans [myDataSource,mySessionFactory,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
SOLUTION:
My test:
import java.util.List;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import com.blah.baseProject.database.DAO.UsuarioDAO;
import com.blah.baseProject.database.model.Usuario;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/applicationContext.xml", "classpath:test-applicationContext.xml" })
#TransactionConfiguration(transactionManager="transactionManager")
public class LoginTest2 extends AbstractTransactionalJUnit4SpringContextTests {
#Autowired
UsuarioDAO usuarioDao;
private final static Logger logger = Logger.getLogger(LoginTest2.class);
#Test
public void test() {
List<Usuario> a = usuarioDao.findAll();
logger.info("hi "+a.get(0).getLogin());
}
}
test-applicationContext.xml and applicationContext.xml remain the same as those specified in the edits to this question.
Your test configuration should only override the beans you don't have in your test (i.e. your datasource). Next you should use the classpath: prefix to load your test configuration file.
Change your test-applicationContext.xml file to the following, which will override the datasource in your applicationContext.xml
<!-- JDBC Data Source. It is assumed you have MySQL running on localhost port 3306 with
username root and blank password. Change below if it's not the case -->
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/myDb"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
<property name="validationQuery" value="SELECT 1"/>
</bean>
Now in your testcase load both files
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:applicationContext.xml", "classpath:test-applicationContext.xml" })
public class LoginTest2 { ... }
The problem with your current setup is that your test-configuration.xml is a (bad) copy of your applicationContext.xml, which is something you should avoid. If you are writing tests you should also load your normal applicationContext.xml file(s) and override the beans you don't need.