search

Home  >  Q&A  >  body text

Spring如何在Java应用程序中自动实现依赖注入

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

巴扎黑巴扎黑2893 days ago646

reply all(6)I'll reply

  • 迷茫

    迷茫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.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 09:53:09

    You need Autowired

    reply
    0
  • PHP中文网

    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

    reply
    0
  • 高洛峰

    高洛峰2017-04-18 09:53:09

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

    reply
    0
  • ringa_lee

    ringa_lee2017-04-18 09:53:09

    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?

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:53:09

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

    reply
    0
  • Cancelreply