Spring:IoC 用法(九、@Bean 用法)

来源:互联网 发布:java sleep使用 编辑:程序博客网 时间:2024/06/06 00:41

Java 配置详解

1、@Configuration

作用:一个 Java 配置类,同等于一个 XML 文件,容器级别配置

用法:

@Configurationpublic class Config {}

2、@Description

作用:描述配置文件的作用

用法:

@Configuration@Description("描述作用:当前这个Java配置无作用,不能重复出现")public class Config {}

3、@Import

作用:引入另一个 Java 配置类,Java 配置之间相互引用

用法:

@Configuration@Import(ControllerConfig.class)public class Config {}

4、@ImportResource

作用: 引入一个XML 配置文件,Java 配置与 XML 混合引用

用法:

@Configuration@ImportResource("classpath:spring/RepositoryConfig.xml")public class Config {}


5、@Bean

作用:注册一个 Bean,对应一个 class 类

特点:1)、默认 id 属性值:方法名,id 其实也属于别名

          2)、别名 name 属性:指定别名后,默认 id 失效

          3)、注入方式 autowire 属性

                  Autowire.NO(默认)

                  Autowire.BY_TYPE

                  Autowire.By_NAME

          4)、初始化方法 initMethod

          5)、销毁方法 destoryMethod

测试:

测试(默认 id 值:id)

定义Controller

public class TestController {    public void testController(){        System.out.println("SUCCESS!!!");    }}

Java配置类

@Configurationpublic class Config {    @Bean    public TestController testController123(){        return new TestController();    }}

测试类

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = Config.class)public class Test {    /**     * 类型注入     */    @Autowired    private TestController c1;    /**     * 别名注入     */    @Autowired    @Qualifier("testController123")    private TestController c2;    @org.junit.Test    public void testXMLConfig() {        c1.testController();        c2.testController();    }}

结果

SUCCESS!!!SUCCESS!!!

测试(指定别名 name)

定义Controller

public class TestController {    public void testController(){        System.out.println("SUCCESS!!!");    }}

Java配置类

@Configurationpublic class Config {    @Bean(name = {"c1","c2"})    public TestController testController123(){        return new TestController();    }}

测试类

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = Config.class)public class Test {    @Autowired    @Qualifier("c1")    private TestController c1;    @Autowired    @Qualifier("c2")    private TestController c2;    @org.junit.Test    public void testXMLConfig() {        c1.testController();        c2.testController();    }}

结果

SUCCESS!!!SUCCESS!!!

测试(注入方式:autowire=no)

定义 Controller 控制层

public class TestController {    private TestService testService;    public TestController(TestService testService) {        this.testService = testService;    }    public void testController() {        System.out.println(testService.testService());    }}

定义 Service 接口

public interface TestService {    String testService();}

定义Service 接口实现

public class TestServiceImpl implements TestService {    public String testService() {        return "This is TestServiceImpl";    }}

Java配置类

@Configurationpublic class Config {    @Bean(autowire = Autowire.NO)    public TestController testController123() {        // 得到注入对象        TestService testService = testService();        // 使用构造方法注入        return new TestController(testService);    }    @Bean    public TestService testService() {        return new TestServiceImpl();    }}

测试类

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = Config.class)public class Test {    @Autowired    private TestController controller;    @org.junit.Test    public void testXMLConfig() {        controller.testController();    }}

结果

This is TestServiceImpl

测试(注入方式:autowire=by_name)

定义 Controller 控制层

public class TestController {    private TestService testService;    public void testController() {        System.out.println(testService.testService());    }    // By_Name 时, 使用反射赋值,Set 方法必须有    public void setTestService(TestService testService) {        this.testService = testService;    }}

定义 Service 接口

public interface TestService {    String testService();}


定义Service 接口实现

public class TestServiceImpl implements TestService {    public String testService() {        return "This is TestServiceImpl";    }}

Java配置类

@Configurationpublic class Config {    @Bean(autowire = Autowire.BY_NAME)    public TestController testController123() {        return new TestController();    }        @Bean    public TestService testService() {        return new TestServiceImpl();    }}

测试类

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = Config.class)public class Test {    @Autowired    private TestController controller;    @org.junit.Test    public void testXMLConfig() {        controller.testController();    }}

结果

This is TestServiceImpl

测试(注入方式:autowire=by_type)

定义 Controller 控制层

<同 autowire = byName>

定义 Service 接口

<同 autowire = byName>

定义Service 接口实现

<同 autowire = byName>

Java配置类

@Configurationpublic class Config {    @Bean(autowire = Autowire.BY_TYPE)    public TestController testController123() {        return new TestController();    }    @Bean    public TestService testService() {        return new TestServiceImpl();    }}


测试类

<同 autowire = byName>

结果

<同 autowire = byName>


测试(初始化 initMethod 方法、销毁 destroy 方法)

定义 Controller 

public class TestController {    public void testController() {        System.out.println("\nSUCCESS!!!");    }    // 初始化方法    public void init() {        System.out.println("this is TestServiceImpl init");    }    // 销毁方法    public void destroy() {        System.out.println("this is TestServiceImpl destroy");    }}

Java 配置文件

@Configurationpublic class Config {    @Bean(initMethod = "init",destroyMethod = "destroy")    public TestController testController123() {        return new TestController();    }}

测试类

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = Config.class)public class Test {    @Autowired    private TestController controller;    @org.junit.Test    public void testXMLConfig() {        controller.testController();    }}

结果

this is TestServiceImpl initSUCCESS!!!this is TestServiceImpl destroy


6、@Profile

作用:不同环境下注册不同的 Bean

          1)、用于 @Configuration 级别上使用

          2)、用于 @Bean 级别上使用

测试:

@Configuration级别测试

定义Controller控制层

public class TestController {    @Autowired    private TestService testService;    public void testController() {        System.out.println(testService.testService());    }}

定义Service接口

public interface TestService {    String testService();}

定义Service接口实现

public class ProServiceImpl implements TestService {    public String testService() {        return "this is ProServiceImpl";    }}

public class TestServiceImpl implements TestService {    public String testService() {        return "This is TestServiceImpl";    }}

Java 配置文件

@Configuration@Import({TestConfig.class, ProConfig.class})public class Config {    @Bean    public TestController testController123() {        return new TestController();    }}

@Configurationpublic class ProConfig {    @Bean    @Profile("pro")    public TestService testService() {        return new ProServiceImpl();    }}

@Configurationpublic class TestConfig {    @Bean    @Profile("test")    public TestService testService(){        return new TestServiceImpl();    }}

测试类

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = Config.class)@ActiveProfiles("pro") // 激活属性文件public class Test {    @Autowired    private TestController controller;    @org.junit.Test    public void testXMLConfig() {        controller.testController();    }}

结果

this is ProServiceImpl

@Bean级别测试

定义Controller控制层

public class TestController {    @Autowired    private TestService testService;    public void testController() {        System.out.println(testService.testService());    }}

定义Service接口

public interface TestService {    String testService();}

定义Service接口实现

public class ProServiceImpl implements TestService {    public String testService() {        return "this is ProServiceImpl";    }}

public class TestServiceImpl implements TestService {    public String testService() {        return "This is TestServiceImpl";    }}

Java 配置文件

@Configurationpublic class Config {    @Bean    public TestController testController123() {        return new TestController();    }    @Bean    @Profile("test")    public TestService testService(){        return new TestServiceImpl();    }    @Bean    @Profile("pro")    public TestService proService() {        return new ProServiceImpl();    }}

测试类

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = Config.class)@ActiveProfiles("pro") // 激活属性文件public class Test {    @Autowired    private TestController controller;    @org.junit.Test    public void testXMLConfig() {        controller.testController();    }}

结果

this is ProServiceImpl


7、@Lazy

作用:延迟加载(默认 true)

          1)、用于 @Configuration 级别上使用

          2)、用于 @Bean 级别上使用

用法:

// Configuration 级别的延迟加载@Configuration@Lazy(value = false)public class Config {    // Bean 级别的延迟加载(就近原则,Bean的优先级大于 Configuration)    @Bean    @Lazy(true)    public TestController testController123() {        return new TestController();    }}

测试:无(通过启动时间或启动日志的方式判断)

8、@Scope

作用:注册 Bean 的使用范围(作用域)

          1)、单例

          2)、原型(多例)

测试:

单例测试:

定义Controller

public class TestController {    private int i;    public void testController() {        System.out.println(i++ + " SUCCESS!!!");    }}

Java配置类

@Configurationpublic class Config {    // 单例    @Bean    @Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)    public TestController testController123() {        return new TestController();    }}

测试类

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = Config.class)public class Test {    @Autowired    private TestController c1;    @Autowired    private TestController c2;    @org.junit.Test    public void testXMLConfig() {        c1.testController();        c2.testController();        if(c1 == c2){            System.out.println("单例模式实例相等。");        }else {            System.out.println("原型模式实例不相等。");        }    }}

结果

0 SUCCESS!!!1 SUCCESS!!!单例模式实例相等。

原型测试:

定义Controller

<同单例不变>

Java配置类

@Configurationpublic class Config {    // 多例    @Bean    @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)    public TestController testController123() {        return new TestController();    }}


测试类

<同单例不变>

结果

0 SUCCESS!!!0 SUCCESS!!!原型模式实例不相等。


9、@DependsOn

作用:实例 Bean 之前,先实例另一个 Bean

测试:(不要在意类的名字)

定义Controller控制层

public class TestController {    public String testController() {        return TestServiceImpl.getValue();    }}

定义初始化数据

public class TestServiceImpl {    private static String value = "初始化数据!!!";    public static void setValue(String value) {        TestServiceImpl.value = value;    }    public static String getValue() {        return value;    }}

定义覆盖数据

public class InitClass {    public InitClass() {        TestServiceImpl.setValue("覆盖初始化数据!!!");    }}

Java配置文件

@Configurationpublic class Config {    @Bean    @DependsOn("init")    public TestController testController123() {        return new TestController();    }    // 使用延迟加载增强显示结果    @Bean(name = "init")    @Lazy    public InitClass initClass() {        return new InitClass();    }}

测试类

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = Config.class)public class Test {    @Autowired    private TestController c1;    @org.junit.Test    public void testXMLConfig() {        String data = c1.testController();        System.out.println(data);    }}

结果

覆盖初始化数据!!!

11、@ Autowired

作用:类型注入方式,如果类型冲突,需要结合@Qualifier(消除get、set方法)

测试:略


12、@Qualifier

作用:别名方式注入,需要集合@Autowrited使用(消除get、set方法)

测试:略


10、@Primary

作用: 当注入发生冲突或者分歧的时候,优先注入原则

测试:

定义 Controller 控制层

public class TestController {    @Autowired    private TestService testService;    public void testController() {        System.out.println(testService.testService());    }}

定义 Service 服务层接口

public interface TestService {    String testService();}

定义 Service 服务层接口实现

public class TestServiceImpl implements TestService {    public String testService() {        return "This is TestServiceImpl";    }}

public class ProServiceImpl implements TestService {    public String testService() {        return "This is ProServiceImpl";    }}

Java配置文件

@Configurationpublic class Config {    /**     * 控制层     */    @Bean    public TestController testController() {        return new TestController();    }    /**     * 服务层:注入两个实现     */    @Bean    public TestService testService() {        return new TestServiceImpl();    }    @Bean    @Primary // 优先使用    public TestService proService() {        return new ProServiceImpl();    }}

测试类

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = Config.class)public class Test {    @Autowired    private TestController controller;    @org.junit.Test    public void testXMLConfig() {        controller.testController();    }}

结果

This is ProServiceImpl

13、@Resource

作用:命名资源依赖注入,别名优先注入,类型其次(消除get、set方法)

测试:

定义Controller

public class TestController {    public void testController() {        System.out.println("SUCCESS!!!");    }}

Java配置文件

@Configurationpublic class Config {    @Bean    public TestController c1() {        return new TestController();    }}

测试类

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = Config.class)public class Test {    @Resource    private TestController c1;    @Resource    private TestController c2;    @org.junit.Test    public void testXMLConfig() {        c1.testController();        c2.testController();    }}

结果

SUCCESS!!!SUCCESS!!!