Reputation: 577
In Spring normally I access a bean using the method getBean(). Eg:
The AplicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www... etc">
<bean id="MyClass" class="ioc.beans.MyClass" />
</beans>
The java:
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
MyClass cl = applicationContext.getBean("MyClass", MyClass.class);
Now I'm working with Spring MVC and beans are created in an xml file with suffix -servlet, and I don't have a ClassPathXmlApplicationContext.
How I can access my java beans from my controller to work with objects, if do not have getBeans method? (Considering also that this method -the first and foremost feature of Spring at any initiation tutorial- is a bad practice).
Upvotes: 0
Views: 1084
Reputation: 6234
If you're using Spring within a web application there's no real reason to programmatically get beans like that.
You should use either explicit constructor/setter injection or autowiring. In the first case, all Spring-managed beans should be defined in your XML (or JavaConfig if you're using it). In the second, the classes to be autowired should either be declared in your XML/JavaConfig or should be on the component scan path.
Upvotes: 1
Reputation: 143
Spring Dependency Injection(Constructor Injection Setter Injection) can be used.
private WildAnimal wild;
@Autowired
public void setWild(WildAnimal wild) {
this.wild = wild;
}
In the Xml
<bean id="wild" class="com.javapapers.spring.ioc.Wolf" />
Upvotes: 1