When I access a bean from spring bean configuration file using BeanFactory like this:
public class Person {
private String id,address;
@Autowired
pri
As @jens suggested
you should active annotation scan
<context:component-scan base-package="package_path">
</context:component-scan>
<context:annotation-config />
hope that helped
When using Spring with an XML context, using annotations is not activated by default. This means @Autowired
, @Transactional
, @PostConstruct
and any other annotation you will use will simply not be exploited.
To make Spring aware of annotations, you need to add the following line:
<context:annotation-config />
Thus, Spring will search for annotations in the beans it creates and process them accordingly.
This requires activating the context
namespace. At the top of your context, make sure you have all context
related links and arguments1:
<beans xmlns="http://www.springframework.org/schema/beans"
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-3.0.xsd">
<context:annotation-config />
<!-- Your context -->
</beans>
You do not need <context:component-scan />
in your case. This would be useful if you used full-annotation context (e.g. classes annotated with @Component
). See the difference between <context:annotation-config />
and <context:component-scan />
in this answer.
As Naman Gala suggested, you could also drop @Autowired
completely and inject all dependencies in XML. See the related answer for more details.
1 This includes the xmlns:context
attribute (xmlns = XML NameSpace) and two URLs in xsi:schemaLocation
.
Approach 1: Include below code in your xml
<beans xmlns="http://www.springframework.org/schema/beans"
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-3.0.xsd">
<context:annotation-config />
<!-- Remaining bean declaration -->
</beans>
Approach 2: Remove @Autowired
and inject customer in your xml file only.
<bean name="person" class="com.ram.spring.model.Person">
<property name="customer" ref="customer"></property>
</bean>
<bean name="customer" class="com.ram.spring.model.Customer">
<property name="email" value="ram@adp.com"></property>
<property name="name" value="Ram"></property>
</bean>
You have to use AnnotationConfigApplicationContext
or
you have to add to yor Spring.xml to activate the annotation scan.