在Spring中如何在Java配置中使用setter注入?

Chr*_*ris 4 java xml spring dependency-injection

我正在尝试学习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>
Run Code Online (Sandbox Code Playgroud)

ceg*_*gas 6

我建议先研究普通的Spring配置,以了解基本事物(例如注入)如何工作。如果您设法在Spring中获得成功,那么该过程在Spring MVC / Spring Boot / etc中将非常相似。就个人而言,我发现一次尝试处理多个概念(视图解析器,不同的配置文件,视图,存储库,多个批注,多种配置方式等)非常令人沮丧,因此我倾向于从最简单的概念开始并构建我的一路攀升。一旦您对注射的工作方式感到满意,就可以轻松地将此知识应用到其他地方。

至于Java配置和注释,它们确实允许更快,更干净的开发。XML非常冗长,难于维护并且非常容易出错,部分原因是在使用基于Java的配置时,IDE通常更有用。也许这就是为什么您阅读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 {}
Run Code Online (Sandbox Code Playgroud)

如果要明确地执行此操作:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您想运行它,只是看它如何工作:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

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

当然,使用Spring Boot,一切都变得更加抽象/快速。