I'm trying to create a simple spring app, but when i use #Component annotation for a bean instead of defining it in spring.xml file, I'm getting this error.
Aug 09, 2017 11:06:03 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#7e32c033: startup date [Wed Aug 09 11:06:03 IST 2017]; root of context hierarchy
Aug 09, 2017 11:06:03 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'oval' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:687)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1207)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1078)
at org.sumit.javabrains.DrawingApp.main(DrawingApp.java:24)
My Classes are al follows:
1. DrawingApp.java (main class)
public package org.sumit.javabrains;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DrawingApp {
public static void main(String[] args) throws InterruptedException {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Oval oval = (Oval) context.getBean("oval");
oval.draw();
}
}
2. Spring.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.sumit.javabrains" />
<context:annotation-config />
<bean id="focus" class="org.sumit.javabrains.Point" scope="singleton">
<property name="x" value="-7" />
<property name="y" value="8" />
</bean>
</beans>
3 Point.java
package org.sumit.javabrains;
public class Point {
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
4 Oval.java
package org.sumit.javabrains;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
#Component
public class Oval {
private Point focus;
public Point getFocus() {
return focus;
}
#Resource
public void setFocus(Point focus) {
this.focus = focus;
}
public void draw() {
System.out.println("Point focus is: ("+focus.getX()+", "+focus.getY()+")");
}
}
could someone be able to help what caused this issue. I'm using spring 4.3.10 RELEASE
That's because your component scan is scanning the wrong packages
<context:component-scan base-package="com.sumit.javabrains" /> - Wrong
It should be scanning as follows:
<context:component-scan base-package="org.sumit.javabrains" /> - Correct
you must define all your bean in spring.xml. in this scenario you missed the Oval class in you spring configuration files. define the Oval class as a bean in your spring.xml file.
or
edit your component-scan tag and put the correct package.
Two thing went wrong here.
1. You've mentioned wrong base package in your xml file
com.sumit.javabrains must be replaced with org.sumit.javabrains
Replace #Resource with #Resource #Qualifier("focus").By default beans marked with ‘#Component’ will have the same name as the class
Try using #ComponentScan instead of #Component on top of the Oval class.
I wasn't using a spring.xml file (just the default spring boot configuration instead), my #SpringBootApplication annotated class was one package level deeper than my #Component class, which made that the #Component class wasn't picked up.
E.g.:
com.company.base/ComponentAnnotatedClass.java
com.company.base.application/MySpringBootApplication.java
Related
Summary: I am working with some sample Spring code (from javabrains.io). Basically this code illustrates the use of the #Qualifier annotation in the Java file. One of the bean elements (in spring.xml) has a qualifier that matches the value of the #Qualifier annotation but even then UnsatisfiedDependencyException is thrown.
Details: The Circle class has a method which accepts a Point object and which has the following annotations:
#Autowired
#Qualifier("circleRelated")
In spring.xml we have three Point beans: pointA, pointB and pointC. pointA has the property attribute set to circleRelated. One would expect that since this bean meets the qualifier criterion (i.e. value = "circleRelated"), at initialization time autowiring should complete without any hitch. However, UnsatisfiedDependencyException is thrown. The source code follows:
Point.java
package org.koushik.javabrains;
public class Point {
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
Circle.java
package org.koushik.javabrains;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Circle {
private Point center;
public Point getCenter() {
return center;
}
#Autowired
#Qualifier("circleRelated")
public void setCenter(Point center) {
this.center = center;
}
public void draw() {
System.out.println("Drawing Circle");
System.out.println("Circle: Center point is: " + center.getX() + ", " + center.getY());
}
}
DrawingApp.java
package org.koushik.javabrains;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DrawingApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Circle circle = (Circle) context.getBean("circle");
circle.draw();
}
}
spring.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"
xmlns:context="http://www.springframework.org/schema/context">
<bean id="pointA" class="org.koushik.javabrains.Point">
<qualifier value="circleRelated"/>
<property name="x" value ="0"/>
<property name="y" value ="0"/>
</bean>
<bean id="pointB" class="org.koushik.javabrains.Point">
<property name="x" value ="-20"/>
<property name="y" value ="0"/>
</bean>
<bean id="pointC" class="org.koushik.javabrains.Point">
<property name="x" value ="20"/>
<property name="y" value ="0"/>
</bean>
<bean id="circle" class="org.koushik.javabrains.Circle">
</bean>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
</beans>
You are missing
<context:annotation-config/>
tag in your spring.xml
Source
Use of these annotations also requires that certain BeanPostProcessors
be registered within the Spring container. As always, these can be
registered as individual bean definitions, but they can also be
implicitly registered by including the following tag in an XML-based
Spring configuration (notice the inclusion of the 'context'
namespace):
On a side note , any specific reason you are using xml based configuration ? Though spring supports xml configurations , it is long since people have moved to Annotations based configuration.I recommend that it is worth exploring annotations based route.
I am facing the below error while executing the below code.
I have my class names as below.
class Dad.java
package TestingDependecy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Dad {
private Mom mom;
private Child child;
public Dad (Mom mom) {
this.mom = mom;
}
public Dad (Child child) {
this.child = child;
}
public void name() throws IOException {
System.out.println("please enter a name ..");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String name = br.readLine();
System.out.println("Please confirm your deatails below");
System.out.println("Your name is "+ name);
}
public void whichWork() {
mom.cooking();
}
public void mainWork() {
System.out.println("Don't distrub me Please...!!");
child.main();
}
}
class Mom.java
package TestingDependecy;
public class Mom {
public void cooking() {
System.out.println("I am cooking ");
System.out.println(" what else i can do ?");
}
}
Class Child
package TestingDependecy;
public class Child {
public void main() {
System.out.println("This is from child class");
}
}
Class Family.java
package TestingDependecy;
import java.io.IOException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import TestingDependecy.Dad;
public class Family {
public static void main(String[] args) throws IOException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
Dad d = context.getBean("dad", Dad.class);
d.mainWork();
System.out.println();
d.whichWork();
context.close();
}
}
Finally my ApplicationContext.xml file as below
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"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- This is for family Package -->
<bean id = "mom"
class="TestingDependecy.Mom">
</bean>
<bean id = "child"
class="TestingDependecy.Child">
</bean>
<bean id = "dad"
class="TestingDependecy.Dad">
<constructor-arg ref="mom"/>
<constructor-arg ref="child"/>
</bean>
I'm getting the below while executing the code.
Please find the error below.
May 04, 2018 8:45:02 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#1a1cd57: startup date [Fri May 04 08:45:01 IST 2018]; root of context hierarchy
May 04, 2018 8:45:02 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [ApplicationContext.xml]
May 04, 2018 8:45:02 AM org.springframework.context.support.AbstractApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dad' defined in class path resource [ApplicationContext.xml]: Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dad' defined in class path resource [ApplicationContext.xml]: Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:243)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1270)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:541)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:501)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
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 TestingDependecy.Family.main(Family.java:13)
Please help me on this, what is the mistake I did here?
Regards,
Saikiran.
in ApplicationContext.xml you've passed two arguments to the constructor of dad bean :
<bean id = "dad"
class="TestingDependecy.Dad">
<constructor-arg ref="mom"/>
<constructor-arg ref="child"/>
</bean>
So you have to define a two-argument constructor in Dad class like this:
public class Dad {
private Mom mom;
private Child child;
public Dad (Mom mom, Child child) {
this.mom = mom;
this.child = child;
}
...
}
NOTE
all keep one constructor and corresponding bean constructor class
<bean id="e" class="com.test.Employee">
<constructor-arg value="12" type="int"></constructor-arg>
<constructor-arg value="UP"></constructor-arg>
<constructor-arg> <ref bean="a1"/> </constructor-arg >
<constructor-arg> <ref bean="company"/> </constructor-arg>
</bean>
public Employee(int idx, String name, Address address, Company company) {
this.idx=idx;
this.name=name;
this.address=address;
this.company=company;
}
I am a new bee to spring and am writing my first spring program.I have the following files.
package com.springstarter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringUser
{
public static void main( String[] args )
{
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
SpringStarter starter = ( SpringStarter ) context.getBean( "springstarter" );
starter.getMessage();
}
}
I have a bean called SpringStarter
package com.springstarter;
public class SpringStarter
{
private String message;
public String getMessage()
{
return message;
}
public void setMessage( String message )
{
this.message = message;
}
}
Beans.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="springstarter" class="com.springstarter.SpringStarter">
<property name="message" value="Hello World!"/>
</bean>
</beans>
The following is the package structure:
I have run the program in eclipse Mars, using Spring 4.2.4.
I didn't find any compilation issues, but the program is just showing the following logs.
Jan 14, 2016 10:36:08 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#73a83205: startup date [Thu Jan 14 10:36:08 IST 2016]; root of context hierarchy
Jan 14, 2016 10:36:08 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Beans.xml]
The expected output though, is Hello World!
Kindly let me know if i'm making any obvious mistakes.
Nothing wrong, but to print the output on console, so you should use it like:
System.out.println(starter.getMessage());
I'm trying to run a simple Spring + Hibernate tutorial => Maven Spring Hibernate annotation example
My beans definition file BeanLocations.xml is like this :
<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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- Database Configuration -->
<import resource="../database/Datasource.xml"/>
<import resource="../database/Hibernate.xml" />
<context:component-scan base-package="com.sample.springhibernate"/>
</beans>
My main method:
public static void main( String[] args )
{
ApplicationContext appContext = new ClassPathXmlApplicationContext("classpath*:BeanLocations.xml");
StockBo stockBo = (StockBo)appContext.getBean("stockBo");
}
I have a defined service with an interface:
public interface StockBo {
public void save(Stock stock);
public void update(Stock stock);
public void delete(Stock stock);
public Stock findByStockCode(String stockCode);
}
And his implementation:
#Service("stockBo")
public class StockBoImpl implements StockBo {
#Autowired
StockDao stockDao;
public void setStockDao(StockDao stockDao){
this.stockDao = stockDao;
}
#Override
public void save(Stock stock) {
stockDao.save(stock);
}
........
There is any problem with this because spring throws a Exception when StockBo)appContext.getBean("stockBo") :
30-oct-2014 15:31:49 org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#64dc11: display name [org.springframework.context.support.ClassPathXmlApplicationContext#64dc11]; startup date [Thu Oct 30 15:31:49 CET 2014]; root of context hierarchy
30-oct-2014 15:31:49 org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
INFO: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext#64dc11]: org.springframework.beans.factory.support.DefaultListableBeanFactory#a3d4cf
30-oct-2014 15:31:49 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#a3d4cf: defining beans []; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'stockBo' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:387)
Spring not foud my annotated service StockBoo (with #Service("stockBo") )....
What is the problem? How can I ensure that Spring recognize my service with component scan?
FYI: StockBo is in com.sample.springhibernate.bo and StockBoImpl in com.sample.springhibernate.bo.impl
If you turn your log level to DEBUG, you'll more than likely find a line like
DEBUG o.s.b.f.xml.XmlBeanDefinitionReader - Loaded 0 bean definitions from location pattern [classpath*:BeanLocations.xml]
That is, your ClassPathXmlApplicationContext did not find any resources that match classpath*:BeanLocations.xml and therefore didn't load any context.
You'll need to provide a resource location String value that properly identifies and locates the context configuration file.
I have a class on which there are several methods and the interface for the class looks something like this
Some main program calls the method doSomeOperation which in turn calls the other methods in the class based on business rule. I have a situation where I have to populate some stats after some of the methods in this class is invoked.
For example, after calling doSomeOperation which in turn calls say doOps1, populate some stats table on the database indicating how many records were inserted/updated/deleted etc in specific table and how much time it took etc by doOps1 method. I am trying to use Spring AOP for this purpose. However the issue that I am facing is that the intended code is not getting invoked.
Here is the full code (for sample purpose only)
package spring.aop.exp;
public interface Business {
void doSomeOperation();
void doOps1();
}
package spring.aop.exp;
public class BusinessImpl implements Business {
public void doSomeOperation() {
System.out.println("I am within doSomeOperation");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
System.out.println("Done with sleeping.");
doOps1();
}
public void doOps1() {
System.out.println("within Ops1");
}
}
The aspect class
package spring.aop.exp;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
#Aspect
public class BusinessProfiler {
#Pointcut("execution(* doOps1*(..))")
public void businessMethods1() { }
#After("businessMethods1()")
public void profile1() throws Throwable {
//this method is supposed to populate the db stats and other statistics
System.out.println("populating stats");
}
}
-- the main class
package spring.aop.exp;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringAOPDemo {
/**
* #param args
*/
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"ExpAOP.xml");
Business bc = (Business) context.getBean("myBusinessClass");
bc.doSomeOperation();
}
}
*and the configuration file***
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<!-- Enable the #AspectJ support -->
<aop:aspectj-autoproxy />
<bean id="businessProfiler" class="spring.aop.exp.BusinessProfiler" />
<bean id="myBusinessClass" class="spring.aop.exp.BusinessImpl" />
</beans>
On running the main program, I am getting the output (and it is not calling profile1 rom the Aspect class - BusinessProfiler). however if I directly call the doOps1 from main class then the aspect method gets invoked. I would like to know if aspect is supposed to work if only called from the main method and not otherwise.
Oct 26, 2012 11:56:19 AM
org.springframework.context.support.AbstractApplicationContext
prepareRefresh INFO: Refreshing
org.springframework.context.support.ClassPathXmlApplicationContext#be2358:
display name
[org.springframework.context.support.ClassPathXmlApplicationContext#be2358];
startup date [Fri Oct 26 11:56:19 EDT 2012]; root of context hierarchy
Oct 26, 2012 11:56:19 AM
org.springframework.beans.factory.xml.XmlBeanDefinitionReader
loadBeanDefinitions INFO: Loading XML bean definitions from class path
resource [ExpAOP.xml] Oct 26, 2012 11:56:19 AM
org.springframework.context.support.AbstractApplicationContext
obtainFreshBeanFactory INFO: Bean factory for application context
[org.springframework.context.support.ClassPathXmlApplicationContext#be2358]:
org.springframework.beans.factory.support.DefaultListableBeanFactory#1006d75
Oct 26, 2012 11:56:19 AM
org.springframework.beans.factory.support.DefaultListableBeanFactory
preInstantiateSingletons INFO: Pre-instantiating singletons in
org.springframework.beans.factory.support.DefaultListableBeanFactory#1006d75:
defining beans
[org.springframework.aop.config.internalAutoProxyCreator,businessProfiler,myBusinessClass];
root of factory hierarchy
*I am within doSomeOperation
Done with sleeping.
within Ops1***
Spring AOP is by default proxy-based and when you call a method on the same class from within another method on that calss, your call doesn't go through the aspect proxy, but directly to the method - that's why your aspect code is not invoked. To understand it better read this chapter of Spring documentation on Understanding AOP proxies.