【问题标题】:How do I use setter injection with java configuration in Spring?如何在 Spring 中将 setter 注入与 java 配置一起使用?
【发布时间】:2017-03-02 16:36:34
【问题描述】:

我正在尝试了解 SpringMVC Web 应用程序中的 setter 注入,我能找到的所有示例均使用 xml 显示。但是,有人告诉我 xml 已被弃用,所有新应用程序都应使用 java 配置完成。这是不对的,我应该使用xml来配置我的应用程序吗?

我应该在哪里声明 bean,我该怎么做?

这是我见过的例子之一,但它是用 xml 实现的。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans 
                       http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="message"
      class="org.springbyexample.di.xml.SetterMessage">
    <property name="message" value="Spring is fun." />
  </bean>

</beans>

【问题讨论】:

    标签: java xml spring dependency-injection


    【解决方案1】:

    我建议首先查看简单的 Spring 配置,以了解基本的东西(如注入)是如何工作的。如果您设法在 Spring 中掌握它,那么在 Spring MVC/Spring Boot/等中该过程将非常相似。就个人而言,我发现尝试同时处理多个概念(视图解析器、不同的配置文件、视图、存储库、多个注释、多种配置方式等)非常令人沮丧,所以我倾向于从最简单的概念开始构建我的一路攀升。一旦您对注入的工作原理感到满意,您就可以轻松地将这些知识应用到其他地方。

    至于 java 配置和注释,它们确实允许更快和更清洁的开发。 XML 非常冗长、难以维护并且很容易出错,部分原因是 IDE 通常在使用基于 java 的配置时更有帮助。也许这就是您读到 XML 已被弃用的原因。除非您确实需要(或对此感兴趣),否则我建议您使用 java/auto 配置而不是 XML 配置。

    现在来看看如何做。一个完整的(但最小的)工作 Spring 示例:

    /* Bean definition
    
    @Component tells Spring that this is a bean. There are a few similar annotations.
    It will be discovered during the component scan, as it has @Component annotation */
    
    package main.java.org.example;
    import org.springframework.stereotype.Component;
    
    @Component 
    public class Greeting {
        private String greeting = "Hello";
    
        public String getGreeting() {
            return this.greeting;
        }
    
        public void setGreeting(String greeting) {
            this.greeting = greeting;
        }
    }
    
    
    /* Another bean definition.
    It has another bean as a dependency, which we inject with a setter. */
    
    package main.java.org.example;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    
    @Component
    public class GreetingCollector {
        private Greeting greeting;
    
        /* This is how you do setter injection */
        @Autowired
        public void setGreeting(Greeting greeting) {
            this.greeting = greeting;
        }
    
        public String getGreeting() {
            return greeting.getGreeting();
        }
    }
    
    
    /* This is a minimal config class. 
    @ComponentScan instructs to look for classes that are 
    annotated with @Component annotation (in other words, beans) */
    
    package main.java.org.example;    
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    
    @ComponentScan
    @Configuration
    public class Config {}
    

    如果你想明确地这样做:

    package main.java.org.example;  
    import main.java.org.example.GreetingCollector;
    import main.java.org.example.Greeting;  
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class Config {
        @Bean
        public Greeting greeting() {
            return new Greeting();
        }
    
        @Bean
        public GreetingCollector greetingCollector(Greeting greeting) {
            return new GreetingCollector(greeting);
        }
    }
    

    如果你想运行它只是为了看看它是如何工作的:

    import main.java.org.example.Config;
    import main.java.org.example.GreetingCollector;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    public class AppContext {
        public static void main(String args[]) {
            System.out.println("Configuring application context...");
            ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
            GreetingCollector collector = (GreetingCollector) context.getBean("greetingCollector");
            System.out.println(collector.getGreeting());
        }
    }
    

    当然,Spring Web 应用程序会有些不同,但基本的注​​入思想是相同的。首先,您需要声明 bean(使用@Bean@Component 或任何其他注释:请参阅herehere 了解差异)。您使用@Autowired 注释setter 或构造函数(甚至是字段),指定参数(不一定需要是具体类- 接口,抽象类也可以),将它们分配给适当的字段。创建一个负责 bean 实例化的配置类。您不需要将组件与配置类放在同一文件夹中,因为您始终可以指定在哪里查找组件。最后,如果您想要更细粒度的控制,您总是可以在配置类中显式声明 bean(所谓的 JavaConfig,而基于 @ComponentScan 的配置有时可能称为 autoconfig)。这应该足以让您入门并为您提供搜索更高级内容的词汇。

    当然,有了 Spring Boot,一切都变得更加抽象/更快。

    【讨论】:

      【解决方案2】:

      但是,有人告诉我,xml 已被弃用,所有新应用程序都应使用 java 配置完成

      XML 并没有被弃用,但是有注释可以让生活变得轻松。那么为什么要使用普通的旧 XML。记住“约定优于配置”

      我应该在哪里声明 bean,我该怎么做?

      我认为你应该在 google 上搜索 @Component、@Configuration、@Bean 等注释。阅读它们你会明白的

      这是我见过的例子之一,但它是用 xml 实现的。

      您会发现许多使用 XML 实现的示例,因为 XML 在 Spring 的早期被广泛使用。 现在随着 Spring 4 和 Spring Boot 的出现。大多数开发人员不会大规模使用 XML。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-20
        • 2020-02-14
        • 1970-01-01
        相关资源
        最近更新 更多