Cannot find class for bean with name defined in class path resource [applicationContext.xml] - spring

I'm posting my query after visiting numerous question posted before on same context, unfortunately none of them resolved my problem. I'm trying a complete xml based configuration in spring without using any annotation. But as soon as i launch the application, i'm getting the following exception.
Cannot find class [com.kashyap.springboot.xml.JdbcConnectionXML.java]
for bean with name 'connection' defined in class path resource
[applicationContext.xml]; nested exception is
java.lang.ClassNotFoundException:
com.kashyap.springboot.xml.JdbcConnectionXML.java
Things i've already taken care of :-
Namespace for component scan re-examined.
Tag for component scan entered.
Bean tag with proper classes' qualified name re-examined.
Bean property and references re-visited.
applicationContext.xml is located on path src/main/resources so no
absolute path required.
Context initialized with ClassPathXmlApplicationContext class.
Classes are already defined with default public constructors for instantiation required by reflection.(though it is not mandatory, used it as precaution). Alas!!! none of the these things worked. Please find the classes and xml below.
package com.kashyap.springboot.xml;
public class JdbcConnectionXML {
public JdbcConnectionXML(){
System.out.println("JDBC XML Constructor Called");
}
}
package com.kashyap.springboot.xml;
public class PrototypeXMLDAO {
public PrototypeXMLDAO(){
System.out.println("PrototypeXMLDAO Constructor Called");
}
private JdbcConnectionXML connection;
public JdbcConnectionXML getConnection() {
return connection;
}
public void setConnection(JdbcConnectionXML connection) {
this.connection = connection;
}
}
package com.kashyap.springboot.xml;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringbootdevApplication {
public static void main(String[] args) {
try (ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");) {
PrototypeXMLDAO pdCDIOne = context.getBean(PrototypeXMLDAO.class);
PrototypeXMLDAO pdCDITwo = context.getBean(PrototypeXMLDAO.class);
System.out.println(pdCDIOne);
System.out.println(pdCDIOne.getConnection());
System.out.println(pdCDITwo);
System.out.println(pdCDITwo.getConnection());
}
}
}
<?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">
<context:component-scan base-package="com.kashyap.springboot.xml" />
<bean id="connection" class="com.kashyap.springboot.xml.JdbcConnectionXML">
</bean>
<bean id="prototype" class="com.kashyap.springboot.xml.PrototypeXMLDAO">
<property name="connection" ref="connection"></property>
</bean>
</beans>
The stack-trace on console as follows:-
Exception in thread "main"
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot
find class [com.kashyap.springboot.xml.JdbcConnectionXML.java] for
bean with name 'connection' defined in class path resource
[applicationContext.xml]; nested exception is
java.lang.ClassNotFoundException:
com.kashyap.springboot.xml.JdbcConnectionXML.java at
org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1380)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:670)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:637)
at
org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1489)
at
org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1007)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:739)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
at
org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:144)
at
org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:85)
at
com.kashyap.springboot.xml.SpringbootdevApplication.main(SpringbootdevApplication.java:13)
Caused by: java.lang.ClassNotFoundException:
com.kashyap.springboot.xml.JdbcConnectionXML.java at
java.net.URLClassLoader.findClass(URLClassLoader.java:381) at
java.lang.ClassLoader.loadClass(ClassLoader.java:424) at
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) at
java.lang.ClassLoader.loadClass(ClassLoader.java:357) at
org.springframework.util.ClassUtils.forName(ClassUtils.java:255) at
org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:418)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1428)
at
org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1372)
... 10 more
If required i'll post the pom.xml too. Any sort of help will be highly appreciated.

Related

I would like to get advice on Spring BeanCreationException Error

This is the person who asked the question just before.
The error on the question was successful, but I was faced with another error.
As a beginner in Spring, there are many things I don't know and
I have a lot of questions to ask. Please understand.
The error code.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'memberService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private dao.IMemberDAO service.MemberService.memberDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [dao.IMemberDAO] 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)}
Related cause: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'memberDao' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean 'sqlSessionFactory' while setting bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [C:\Users\admin\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\rachelivf\WEB-INF\classes\dao\mapper\memberDaoMapper.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'member'. Cause: java.lang.ClassNotFoundException: Cannot find class: member
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
The following is the MemberService.java code.
package service;
import java.util.HashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import dao.IMemberDAO;
import model.Member;
#Service
public class MemberService
{
#Autowired
private IMemberDAO memberDao;
public void joinMember(HashMap<String, Object> params)
{
if(params.get("pw").equals(params.get("pwd_CHECK")))
{
memberDao.insertMember(params);
}
}
}
Here is the applicationContext.xml code.
<?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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.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-4.1.xsd">
<context:component-scan base-package="service" />
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
<property value="com.mysql.jdbc.Driver" name="driverClassName"></property>
<property value="jdbc:mysql://localhost/rachelvf" name="url"></property>
<property value="root" name="username"/>
<property value="mysql" name="password"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mapperLocations" value="classpath*:dao/mapper/*.xml"></property>
</bean>
<bean id="memberDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
<property name="mapperInterface" value="dao.IMemberDAO"></property>
</bean>
</beans>
As far as I know,
this is the reason why the above error occurs because
I didn't insert the annotation service.
But obviously I inserted the Service annotation, but I get an error.
Please give me advice.
It is memberDaoMapper code.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.IMemberDAO">
<insert id="insertMember" parameterType="java.util.HashMap">
insert into member values
(
#{id},#{pw},default
)
</insert>
<update id="updateMember" parameterType="java.util.HashMap">
update member set id = #{id}, pw = #{pw}, authority = #{authority}
</update>
<delete id="deleteMember" parameterType="String">
delete from member where id = #{id}
</delete>
<select id="selectOne" parameterType="String" resultType="member">
select * from member where id = #{id}
</select>
<select id="selectAll" parameterType="String" resultType="member">
select * from member
</select>
</mapper>
It is IMemberDao.java code.
package dao;
import java.util.HashMap;
import java.util.List;
import org.mybatis.spring.annotation.MapperScan;
import model.Member;
public interface IMemberDAO
{
public int insertMember(HashMap<String, Object> params);
public int updateMember(HashMap<String, Object> params);
public int deleteMember(String id);
public HashMap<String, Object> selectOne(String id);
public List<HashMap<String, Object>> selectAll();
}
I checked the typo thoroughly, but there was no typo to be found.
What's the problem?
This part of the stacktrace should give you a proper hint of the issue:
org.apache.ibatis.type.TypeException: Could not resolve type alias 'member'
Without the mapper files, I suppose that there is an error in one of them and probably you wrote member in an XML attribute that requires a fully qualified class name.
My suggestion is to search member in those file and you should find it in an incorrect field (mostly like parameterType or resultType)
Looking at the Mapping file that you added, you have resultType="member". As stated above resultType requires a fully qualified class name.
The solutions to your issue are mostly 2:
Modify the resultType to the actual class
<select id="selectOne" parameterType="String" resultType="model.Member">
select * from member where id = #{id}
</select>
<select id="selectAll" parameterType="String" resultType="model.Member">
select * from member
</select>
Add type alias tag for sampleVO class.
<mapper namespace="model.Member">
<typeAlias alias="member" type="model.Member" />
...
</mapper>

Spring:Error creating bean with name 'edao' defined in class path resource [applicationContext.xml]

I am new new to spring programming.While executing a program for fetching some records from mysql database i am getting these errors:
log4j:WARN No appenders could be found for logger (org.springframework.beans.factory.xml.XmlBeanDefinitionReader).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'edao' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'jtemplate' while setting bean property 'jdbcTemplate'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jtemplate' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'ds' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ds' defined in class path resource [applicationContext.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClassName' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [com.mysql.jdbc.Driver]
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:275)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:104)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1245)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at Test.main(Test.java:15)
I have three files in my project.
1.EmpDAO.java:
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
public class EmpDAO {
private JdbcTemplate template;
public JdbcTemplate getTemplate() {
return template;
}
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public List<Student> getAllStudents(){
return (List<Student>) template.query("select * from test",new ResultSetExtractor(){
#Override
public List<Student> extractData(ResultSet rs) throws SQLException,
DataAccessException {
List<Student> list=new ArrayList<Student>();
while(rs.next()){
Student e=new Student();
e.setName(rs.getString(1));
e.setRoll(rs.getString(2));
list.add(e);
}
return list;
}
});
}
}
2.Student.java:
public class Student {
private String name;
private String roll;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRoll() {
return roll;
}
public void setRoll(String roll) {
this.roll = roll;
}
public void display(){
System.out.println("Name: "+name+" Roll="+roll);
}
}
3.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/test" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
<bean id="jtemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg ref="ds"></constructor-arg>
</bean>
<bean id="edao" class="EmpDAO">
<property name="jdbcTemplate" ref="jtemplate"></property>
</bean>
</beans>
4.Test.java(for execution):
import java.util.List;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Resource resource=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(resource);
EmpDAO dao=(EmpDAO)factory.getBean("edao");
List<Student> list=dao.getAllStudents();
for(Student e:list)
System.out.println(e);
}
}
The jars that i included in reference library:
These are the jars i included
Kindly help me in this regards.A prevalentines day thank you is in advance.
The relevant part of your errormessage is:
java.lang.IllegalStateException: Could not load JDBC driver class [com.mysql.jdbc.Driver]
You can download that jar from here: 5.1.38, or look for different versions on the central nexus repository.
Note: you would be much better of employing some dependency management system, rather than doing this manually. I suggest taking a look at Maven.

Cannot find class [main.java.OutputHelper] for bean with name 'OutputHelper' defined in class path resource

I am new to Spring. I am creating simple project in which I just call generateOutout() method using beans.
IOutputGenerator Interface:
package mian.java;
public interface IOutputGenerator {
public void generateOutput();
}
CsvOutputGenerator.java (implements IOutputGenerator ):
package mian.java;
public class CsvOutputGenerator implements IOutputGenerator{
public void generateOutput(){
System.out.println("Csv Output Generator");
}
}
JsonOutputGenerator.java (implements IOutputGenerator ):
package mian.java;
public class JsonOutputGenerator implements IOutputGenerator {
public void generateOutput(){
System.out.println("Json Output Generator");
}
}
OutputHelper.java:
package mian.java;
public class OutputHelper {
IOutputGenerator outputGeneratorCsv;
IOutputGenerator outputGeneratorJson;
public void generateOutput(){
outputGeneratorCsv.generateOutput();
outputGeneratorJson.generateOutput();
}
public void setOutputGenerator(IOutputGenerator outputGeneratorCsv,IOutputGenerator outputGeneratorJson){
this.outputGeneratorCsv = outputGeneratorCsv;
this.outputGeneratorJson = outputGeneratorJson;
}
}
AppViaSpring.java (Main class):
package mian.java;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AppViaSpring {
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"Spring-Common.xml"});
OutputHelper output = (OutputHelper)context.getBean("OutputHelper");
output.generateOutput();
}
}
Spring-Common.xml (Bean Class in main.resources package):
<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-2.5.xsd">
<bean id="OutputHelper" class="main.java.OutputHelper">
<property name="outputGeneratorCsv" ref="CsvOutputGenerator" />
</bean>
<bean id="CsvOutputGenerator" class="main.java.CsvOutputGenerator" />
<bean id="JsonOutputGenerator" class="main.java.JsonOutputGenerator" />
</beans>
and Error is :
Exception in thread "main" org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [main.java.OutputHelper] for bean with name 'OutputHelper' defined in class path resource [Spring-Common.xml]; nested exception is java.lang.ClassNotFoundException: main.java.OutputHelper
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1141)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:524)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1177)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:758)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:422)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
at mian.java.AppViaSpring.main(AppViaSpring.java:10)
Caused by: java.lang.ClassNotFoundException: main.java.OutputHelper
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)
at org.springframework.util.ClassUtils.forName(ClassUtils.java:211)
at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:385)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1138)
... 9 more
you forgot to add the JsonOutputGenerator bean for OutputHelper
try this:
<bean id="OutputHelper" class="main.java.OutputHelper">
<property name="outputGeneratorCsv" ref="CsvOutputGenerator" />
<property name="outputGeneratorJson" ref="JsonOutputGenerator" />
</bean>
note you can also use context.getBean(OutputHelper.class), no casting will be required
edit:
on the further look at the problem. The setter you are using has two arguments which violates javaBean convention. There are few options.
1. You simply pass the map to the setter.
2. Create setter for each generator field.
3. You inject outputGeneratorCsv and outputGeneratorJson in the constructor - i would recommend that. In that case you would have to add constructor with two arguments (like your setter method) and modify the spring context xml to something like that:
<bean id="OutputHelper" class="main.java.OutputHelper">
<constructor-arg ref="outputGeneratorCsv"/>
<constructor-arg ref="outputGeneratorJson"/>
</bean>
here also some more info, why to use constructor injections:
We usually advise people to use constructor injection for all mandatory collaborators and setter injection for all other properties. Again, constructor injection ensures all mandatory properties have been satisfied, and it is simply not possible to instantiate an object in an invalid state (not having passed its collaborators). In other words, when using constructor injection you do not have to use a dedicated mechanism to ensure required properties are set (other than normal Java mechanisms).
Setter injection versus constructor injection

EJB3 interceptor cannot bootstrap context

I'm trying to inject Spring beans into an EJB using
#Interceptors(SpringBeanAutowiringInterceptor.class)
Here's my EJB:
#Stateless
#Interceptors(SpringBeanAutowiringInterceptor.class)
public class processMethodService implements
processMethodService {
#Autowired
private SomeBean bean;
#Schedule(minute = "*/5", hour = "*", persistent = false)
#TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void startProcessing() {
//businesslogic
}
}
And beanRefContext.xml as follows
<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-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<bean id="ejb-businesslayer.application.context" lazy-init="true"
class="org.springframework.context.support.ClassPathXmlApplicationContext">
<constructor-arg>
<list>
<value>classpath:/META-INF/spring-config.xml</value>
</list>
</constructor-arg>
</bean> `
beanRefContext.xml,spring-config.xml are under META-INF folder.
when startProcessing is called for every 5 minutes and we are getting the below exception
Exception data: javax.ejb.EJBException: session bean lifecycle interceptor failure;nested exception is:org.springframework.beans.factory.access.BootstrapException: Unable to return specified BeanFactory instance: factory key [null],
from group with resource name [classpath*:beanRefContext.xml];
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [org.springframework.beans.factory.BeanFactory] is defined
Please find the complete exception as below
Exception data: javax.ejb.EJBException: session bean lifecycle interceptor failure;nested exception is: org.springframework.beans.factory.access.BootstrapException: Unable to return specified BeanFactory instance: factory key [null], from group with resource name [classpath*:beanRefContext.xml]; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.beans.factory.BeanFactory] is defined`enter code here`
at com.ibm.ejs.container.util.ExceptionUtil.EJBException(ExceptionUtil.java:466)
at com.ibm.ejs.container.SessionBeanO.callLifecycleInterceptors(SessionBeanO.java:288)
at com.ibm.ejs.container.StatelessBeanO.initialize(StatelessBeanO.java:399)
at com.ibm.ejs.container.BeanOFactory.create(BeanOFactory.java:147)
at com.ibm.ejs.container.EJSHome.createBeanO(EJSHome.java:1238)
at com.ibm.ejs.container.EJSHome.createBeanO(EJSHome.java:1356)
at com.ibm.ejs.container.activator.UncachedActivationStrategy.atActivate(UncachedActivationStrategy.java:88)
at com.ibm.ejs.container.activator.Activator.preInvokeActivateBean(Activator.java:615)
at com.ibm.ejs.container.EJSContainer.preInvokeActivate(EJSContainer.java:4205)
at com.ibm.ejs.container.EJSContainer.EjbPreInvoke(EJSContainer.java:3535)
at com.ibm.ejs.container.TimedObjectWrapper.invokeCallback(TimedObjectWrapper.java:110)
at com.ibm.ejs.container.TimerNpListener.doWork(TimerNpListener.java:293)
at com.ibm.ejs.container.TimerNpListener.doWorkWithRetries(TimerNpListener.java:171)
at com.ibm.ejs.container.TimerNpListener.fired(TimerNpListener.java:141)
at com.ibm.ws.asynchbeans.AlarmImpl.callListenerMethod(AlarmImpl.java:427)
at com.ibm.ws.asynchbeans.timer.GenericTimer.run(GenericTimer.java:228)
at com.ibm.ws.asynchbeans.J2EEContext.run(J2EEContext.java:1178)
at com.ibm.ws.asynchbeans.AlarmImpl.runListenerAsCJWork(AlarmImpl.java:249)
at com.ibm.ws.asynchbeans.am._Alarm.fireAlarm(_Alarm.java:333)
at com.ibm.ws.asynchbeans.am._Alarm.run(_Alarm.java:230)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1783)
Caused by: org.springframework.beans.factory.access.BootstrapException: Unable to return specified BeanFactory instance: factory key [null], from group with resource name [classpath*:beanRefContext.xml]; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.beans.factory.BeanFactory] is defined
at org.springframework.beans.factory.access.SingletonBeanFactoryLocator.useBeanFactory(SingletonBeanFactoryLocator.java:402)
at org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor.getBeanFactoryReference(SpringBeanAutowiringInterceptor.java:160)
at org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor.getBeanFactory(SpringBeanAutowiringInterceptor.java:141)
at org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor.doAutowireBean(SpringBeanAutowiringInterceptor.java:121)
at org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor.autowireBean(SpringBeanAutowiringInterceptor.java:95)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:88)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
at java.lang.reflect.Method.invoke(Method.java:613)
at com.ibm.ejs.container.interceptors.InterceptorProxy.invokeInterceptor(InterceptorProxy.java:227)
at com.ibm.ejs.container.interceptors.InvocationContextImpl.proceed(InvocationContextImpl.java:548)
at com.ibm.ejs.container.interceptors.InvocationContextImpl.doLifeCycle(InvocationContextImpl.java:273)
at com.ibm.ejs.container.SessionBeanO.callLifecycleInterceptors(SessionBeanO.java:274)
Please guide me on how to resolve this error
The ContextSingletonBeanFactoryLocator is looking for resource classpath*:beanRefContext.xml, so the beanRefContext.xml file has to be in the classpath, ref this link,
Move beanRefContext.xml into a folder that's in the class path and that should solve the problem.
First off, I think removing META-INF should help. Also, I just solved this same issue by moving context in question to /resources directory

Use Spring AOP on class with final members and no default constructor

I am trying to use spring aop.
I have configured the following Aspect:
#Component
#Aspect
public class BenchmarkAspect {
private static final Logger logger = LoggerFactory.getLogger(BenchmarkAspect.class);
#Around(value = "#annotation(benchmark)")
public void do(final ProceedingJoinPoint joinPoint, final Benchmark benchmark) throws Throwable {
logger.error("Before");
joinPoint.proceed();
logger.error("After");
}
And this is an example for a class using my costume annotation
#Component
public class AttributeContainer {
private static final Logger logger = LoggerFactory.getLogger(AttributeContainer.class);
private final int y;
public AttributeContainer(int y){
this.y = y;
}
#Benchmark
public void getAttribute() {
logger.error("Inside Attribute call...");
}
}
When I load my application I get the following exception:
nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.test.AttributeContainer]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Superclass has no null constructors but no arguments were given:
java.lang.IllegalArgumentException: Superclass has no null constructors but no arguments were given
at net.sf.cglib.proxy.Enhancer.emitConstructors(Enhancer.java:721)
at net.sf.cglib.proxy.Enhancer.generateClass(Enhancer.java:499)
at net.sf.cglib.transform.TransformingClassGenerator.generateClass(TransformingClassGenerator.java:33)
at net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
at net.sf.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
at net.sf.cglib.proxy.Enhancer.create(Enhancer.java:285)
at org.springframework.aop.framework.Cglib2AopProxy.getProxy(Cglib2AopProxy.java:201)
at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:112)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:476)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:362)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:322)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:407)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1461)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:848)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:790)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
Update
Adding my spring config xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<aop:aspectj-autoproxy proxy-target-class="true"/>
<context:component-scan base-package="com.test.*" />
<bean id="test" class="com.test.AttributeContainer">
<constructor-arg value="34"/>
</bean>
</beans>
Why the CGlib is failing to create a sub class??
Thanks!
please define a no args public or default type constructor inside the class of targeted method for adviceMethod.Hope, it will resolve your issue.
Could not instantiate bean class [...]: No default constructor found
This looks more like a Spring bean configuration/instantiation problem than anything connected with Spring AOP or AspectJ.
After you will have fixed this, you will probably run into other problems:
In your advice #Around(value = "#annotation(benchmark)") you should take care of spelling. I guess you want your annotation Benchmark to begin with a capital "B", not a lower-case one.
Where does your second advice parameter final Benchmark benchmark come from? It is not bound via args, this or target. You do not use it in your advice anyway, so you can just remove it.
Update to answer your additional question:
AopConfigException: Could not generate CGLIB subclass of class
[class com.test.AttributeContainer]: Common causes of this problem
include using a final class or a non-visible class;
nested exception is java.lang.IllegalArgumentException:
Superclass has no null constructors but no arguments were given
This exception message seems pretty self-explanatory. Have you read it? You instantiate your component without parameters, but only provide a constructor which absolutely needs a parameter. This is why Spring complains. Maybe you want to read a Spring tutorial?

Resources