Spring如何在Java应用程序中自动实现依赖注入
巴扎黑
巴扎黑 2017-04-18 09:51:09
0
6
609

最近开发一个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

巴扎黑
巴扎黑

reply all(6)
迷茫

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.

Peter_Zhu

You need Autowired

洪涛

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

小葫芦

You have to treat your HELLO as a member variable, and then go to @autowired or @Resourse

左手右手慢动作

Dependency injection is nothing more than two steps:

  1. declare bean

  2. Inject beans

How to declare a bean:

  1. In xml

  2. Add @Component, @Service, etc. to the class

  3. Write the method with @Bean in the class with @Configuration

How to inject beans:

  1. In xml

  2. 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

  1. There is no need to configure listener in web.xml in web applications (the prerequisite is servlet3.0+, such as tomcat7+)

  2. For Java Application, why not try Spring boot?

Ty80

Recommended topic owner can take a look @Chachage Servlet 3 + Spring MVC zero configuration: remove all xml

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template