CannotLoadBeanClassException when try to get a bean from applicationContext.xml - java

i have just started a course about Spring framework and i am struggling getting over this exceiption:
Exception in thread "main" org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [TrackCoach] for bean with name 'myCoach' defined in class path resource [applicationContext.xml]; nested exception is java.lang.ClassNotFoundException: TrackCoach
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1476)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:682)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:649)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1604)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1080)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:859)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:144)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:85)
at com.love2code.springdemo.HelloSpringApp.main(HelloSpringApp.java:9)
This is my main class:
package com.love2code.springdemo;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloSpringApp {
public static void main(String[] args) {
//load the spring configuration file
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//retrieve bean from spring container
Coach theCoach = context.getBean("myCoach", Coach.class);
//call methods on the bean
System.out.println(theCoach.getDailyWorkout());
//close the context
context.close();
}
}
My TrackCoach class:
package com.love2code.springdemo;
public class TrackCoach implements Coach {
#Override
public String getDailyWorkout() {
return "Smoke 2 bl's";
}
}
And 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: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">
<!-- Define your beans here -->
<bean id="myCoach" class="com.luv2code.springdemo.TrackCoach">
</bean>
</beans>
Could someone help me out with this please?

Related

Spring #Autowire when using multi-level interfaces

I want to find a solution to configure my spring to support multi-level inheritance of interfaces.The considered scenario is as follow:
public class MainClass {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("Beans.xml");
TextEditor te = (TextEditor) ctx.getBean("textEditor");
te.spellCheck();
}
//--------------------
#Component
public class TextEditor {
#Autowired
private SpellChecker1 spellChecker;
public void spellCheck() {
spellChecker.checkSpelling();
}
}
//--------------------
public interface SpellChecker1 extends SpellChecker2{
}
//--------------------
public interface SpellChecker2 {
public void checkSpelling();
}
//--------------------
#Service
public class SpellCheckerImpl implements SpellChecker2 {
public SpellCheckerImpl() {
System.out.println("Inside SpellChecker constructor.");
}
#Override
public void checkSpelling() {
System.out.println("Inside checkSpelling.");
}
}
//--------------------
Also, my Beans.xml file is contain:
<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.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.mycompany.test"/>
<bean id="textEditor" class="com.mycompany.test.TextEditor" >
</bean>
</beans>
//The following error is issued when running the the MainClass
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'textEditor': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mycompany.test.SpellChecker1 com.mycompany.test.TextEditor.spellChecker; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.mycompany.test.SpellChecker1] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.

Java spring 'Hello World' example couldn't compile

As a HelloWorld example, in my spring Beans.xml file, I have:
<?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-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld">
<property name = "message" value = "Hello World!"/>
</bean>
</beans>
The main file:
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
}
}
The class file:
package com.tutorialspoint;
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
The error seems like this:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'helloWorld' defined in class path resource [Beans.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.tutorialspoint.HelloWorld]: Is the constructor accessible?; nested exception is java.lang.IllegalAccessException: class org.springframework.beans.BeanUtils (in module spring.beans) cannot access class com.tutorialspoint.HelloWorld (in module HelloSpring) because module HelloSpring does not export com.tutorialspoint to module spring.beans
at spring.beans#5.2.5.RELEASE/org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1320)
at spring.beans#5.2.5.RELEASE/org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1214)
at spring.beans#5.2.5.RELEASE/org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
at spring.beans#5.2.5.RELEASE/org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at spring.beans#5.2.5.RELEASE/org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at spring.beans#5.2.5.RELEASE/org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at spring.beans#5.2.5.RELEASE/org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at spring.beans#5.2.5.RELEASE/org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at spring.beans#5.2.5.RELEASE/org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:882)
at spring.context#5.2.5.RELEASE/org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
at spring.context#5.2.5.RELEASE/org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at spring.context#5.2.5.RELEASE/org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:144)
at spring.context#5.2.5.RELEASE/org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:85)
at HelloSpring/com.tutorialspoint.MainApp.main(MainApp.java:8)
Other folks on this site got the same problem, and I've looked at it. However, I've tried all the answers provided but none of them solved my issue. I've used several versions of the path inside and there's no empty line above the first line of my Beans.xml. What's the problem here?

No qualifying bean of type available

Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.spring.dto.Car2' available
Controller.java -
public class Controller {
public static void main(String[] args) {
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("configu.xml");
Car2 c2 = (Car2) context.getBean(Car2.class);
System.out.println(c2);
}
}
Car2.java -
#ToString #Component
public class Car2 {
#Autowired
private Engine engine;
}
Engine.java -
#Setter #ToString
public class Engine {
private String modelYear;
}
configu.xml -
<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.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.spring.dto.Car2" />
<context:annotation-config />
<bean class="com.spring.dto.Engine">
<property name="modelYear" value="2015"></property>
</bean>
</beans>
please ignore the annotation #ToString and #Setter- I am using Lombok project for my simplicity.
I think the error is here:
<context:component-scan base-package="com.spring.dto.Car2" />
The value should be a package, not a class. Change it to "com.spring.dto", then it should work.

BeanCreationException : Injection of autowired dependencies failed

I have 2 classes in 2 different projects, and I have some difficulties to autowire a field.
In project pack, I have this Computation class :
package fr.aaa;
#Component
public class Computation {
#Autowired
#Qualifier("curveDAO")
CurveAccess curveDAO;
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:applicationContext.xml");
}
}
In project db, I have this CurveAccess interface :
package com.bbb
public interface CurveAccess {
// some methods
}
implemented by a CurveDAO class :
package com.bbb.impl
#Repository("curveDAO")
#Transactional("cvaTxManager")
public class CurveDAO implements CurveAccess {
// some methods
}
My applicationContext.xml file from pack project :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
xmlns:security="http://www.springframework.org/schema/security" xmlns:context="http://www.springframework.org/schema/context"
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.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">
<import resource="classpath:spring/persistence.xml"/>
<context:annotation-config />
<context:component-scan base-package="fr.aaa.*, com.bbb.*"/>
<util:properties id="jdbcProps" location="jdbc.properties" />
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:configuration.properties</value>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
When running, I have this exception :
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'Computation': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.bbb.CurveAccess fr.aaa.Computation.curveDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.bbb.CurveAccess] 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), #org.springframework.beans.factory.annotation.Qualifier(value=curveDAO)}
How can I solve this problem ?
Actually, your code works perfectly fine:
#SpringBootApplication
public class So21481801Application implements CommandLineRunner {
public interface CurveAccess {
String hello();
}
#Repository("curveDAO")
public class CurveDAO implements CurveAccess {
#Override
public String hello() {
return "Hello";
}
}
#Repository("curveDAOWorld")
public class CurveDAOWorld implements CurveAccess {
#Override
public String hello() {
return "World";
}
}
#Autowired
#Qualifier("curveDAO")
CurveAccess curveDAO;
#Autowired
#Qualifier("curveDAOWorld")
CurveAccess curveDAOWorld;
#Override
public void run(String... args) {
System.out.println(curveDAO.hello());
System.out.println(curveDAOWorld.hello());
}
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(So21481801Application.class, args);
context.close();
}
}
Probably you have some problem on how you are using the component-scan configuration on XML and the Java annotations. Mix them is not a good idea.
You need a class that implements CurveAccess interface
#Component
public class CurveAccessImpl implements CurveAccess {
//methods
}
Also remove Qualifier from curveDao in Computation bean since there is no such bean with id curveDao.
#Autowired
CurveAccess curveDAO;

How do I use spring property sources within a child annotation context?

I'm trying to replicate something that works with XML config using annotated configuration classes. The problem I'm hitting is that property sources defined in the child context are not accessible.
The xml that works looks like
Parent context :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="proxyChannelQueue" class="java.util.concurrent.ArrayBlockingQueue">
<constructor-arg value="10"/>
</bean>
</beans>
Child Context :
<?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:p="http://www.springframework.org/schema/p"
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:property-placeholder location="proxy-host.properties"/>
<bean class="org.eclipse.jetty.server.Server"
p:handler-ref="proxyHostHandler"
init-method="start">
<constructor-arg value="${proxyHostPort}"/>
</bean>
<bean id="proxyHostHandler" class="com.sjl.web.ProxyHostHandler"
p:proxyChannelQueue-ref="proxyChannelQueue"/>
</beans>
Start up code :
ClassPathXmlApplicationContext parentContext = new ClassPathXmlApplicationContext("test/parent-context.xml");
ClassPathXmlApplicationContext childContext = new ClassPathXmlApplicationContext(new String[] {"test/child-context.xml"}, parentContext);
My attempt at doing this using configuration classes looks like.
Parent Context :
#Configuration
public class ParentConfiguration {
#Bean(name = "proxyChannelQueue")
public BlockingQueue<ProxyChannel> getProxyChannelQueue() {
return new ArrayBlockingQueue<ProxyChannel>(10);
}
}
Child Context :
#Configuration
#PropertySource("classpath:proxy-host.properties")
public class ChildContext {
private static final Logger LOGGER = LoggerFactory.getLogger(ChildContext.class);
#Autowired
private Environment environment;
#Resource(name = "proxyChannelQueue")
private BlockingQueue<ProxyChannel> proxyChannelQueue;
public static void main(String[] args) {
new HierarchicalAnnotationConfigApplicationContext(ChildContext.class);
}
#Bean
public Server getJettyServer() throws Exception {
int proxyHostPort = environment.getProperty("proxyHostPort", Integer.class);
Server server = new Server(proxyHostPort);
server.setHandler(getHandler());
server.start();
return server;
}
#Bean
public Handler getHandler() {
ProxyHostHandler proxyHostHandler = new ProxyHostHandler();
proxyHostHandler.setProxyChannelQueue(proxyChannelQueue);
return proxyHostHandler;
}
}
Start up code :
AnnotationConfigApplicationContext parentContext = new AnnotationConfigApplicationContext(ParentConfiguration.class);
AnnotationConfigApplicationContext childContext = new AnnotationConfigApplicationContext();
childContext.setParent(parentContext);
childContext.register(ChildContext.class);
childContext.refresh();
I'm getting a null pointer while trying to retrieve the proxyHostPort within the ChildContext getJettyServer method. Inspecting the environment variable shows that it contains only 2 property sources (systemProperties and systemEnvironment) and not the 3 I expect.
The same configuration works if I run them as a single combined context. E.g. :
AnnotationConfigApplicationContext parentContext = new AnnotationConfigApplicationContext(ParentConfiguration.class, ChildContext.class);
However I want the isolation that using parent contexts provide.
Cheers,
Peter

Categories