史上最简单SpringBoot @Bean & @Qualifier 注入(零 XML 注入)

首先,Create 一个名叫 ApplicationConfig 的类:
—> 1、用 @Configuration 注解上
—> 2、继承 WebMvcConfigurerAdapter (零 XML 注入)
—> 3、定义一个方法用 @Bean 注解在此方法上

import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;

@Configuration
public class ApplicationConfig extends WebMvcConfigurerAdapter {

    @Bean("testInterface")
    public TestInterface testInterface() {

        return new TestInterfaceImpl();
    }
}

然后,在 Controller 或 ServiceImpl 层 就可直接用 @Autowired & @Qualifier 注入了:
—> @Bean("…") 必须与 @Qualifier("…") 括号里面的值必须一样

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

@RestController
@RequestMapping("/test")
public class CsMcmsErrorMessageController {

    @Autowired
    @Qualifier("testInterface")
    private TestInterface testInterface;

}

你可能感兴趣的:(史上最简单SpringBoot @Bean & @Qualifier 注入(零 XML 注入))