最近开发一个Java应用程序,希望能使用Spring来实现依赖注入。
在Web应用程序中,可以在web.xml文件中配置listener来自动实现注入。
在Java Application中,可以通过如下的方式来加载Spring:
ClassPathXmlApplicationContext ctx = new FileSystemXMLApplicationContext("beans.xml");
Hello hello = ctx.getBeans("hello");
但这样的一个问题是,在每次使用一个bean时,都需要显示调用一次getBeans。
不知有什么好的方法,能够让Spring自动加载对象,而不需要显式调用getBeans?
更多 0
迷茫2017-04-18 09:53:09
Write two more lines following your example.
public class Main{
public static void main(String[] args){
ClassPathXmlApplicationContext ctx = new FileSystemXMLApplicationContext("beans.xml");
Hello hello = ctx.getBeans("hello");
hello.say();
}
}
class Hello {
@Autowired
private DbUtil db;
public void say(){
System.out.println(db.getWelcomeInfo());
}
}
The layer that initially handles requests in the web project still needs to be generated through getBeans(). It's just that this step is done by tomcat/strtus/springMVC.
Spring will automatically inject classes managed by it. However, the main class started by your program is not generated by Spring management.
PHP中文网2017-04-18 09:53:09
To use Spring's dependency injection, you must first obtain the bean from Spring, so as to ensure that the bean's dependencies have been injected. If you create a new object yourself, how can Spring inject it for you?
You can encapsulate the getBeans method yourself
高洛峰2017-04-18 09:53:09
You have to treat your HELLO as a member variable, and then go to @autowired or @Resourse
ringa_lee2017-04-18 09:53:09
Dependency injection is nothing more than two steps:
declare bean
Inject beans
How to declare a bean:
In xml
Add @Component, @Service, etc. to the class
Write the method with @Bean in the class with @Configuration
How to inject beans:
In xml
Annotations like @Autowire
It may not be all mentioned, but these should be the commonly used ones. For details, please refer to the spring documentation and ioc part
Let’s ask a question
There is no need to configure listener in web.xml in web applications (the prerequisite is servlet3.0+, such as tomcat7+)
For Java Application, why not try Spring boot?
PHP中文网2017-04-18 09:53:09
Recommended topic owner can take a look @Chachage Servlet 3 + Spring MVC zero configuration: remove all xml