Spring装配Bean -- 自动化装配Bean

Spring从两个角度来实现自动化装配:

        组件扫描(component scanning):Spring会自动发现应用上下文中所创建的Bean

        自动装配(autowiring):Spring自动满足Bean之间的依赖

组件扫描和自动装配组合在一起能将显式配置降低到最少


创建可被发现的Bean:

        创建CD接口:

package main.java.Demo1;

/**
 * @author myvina@qq.com
 * @date 18-4-15 下午6:53
 */

public interface CompactDisc {
    void play();
}
        创建BeatlesCD类实现CD接口:
package main.java.Demo1;

import org.springframework.stereotype.Component;

/**
 * @author myvina@qq.com
 * @date 18-4-15 下午8:50
 */

@Component
public class BeatlesCD implements CompactDisc {
    @Override
    public void play() {
        System.out.println("Playing Beatles");
    }
}

        使用@Component注解表明该类会作为组件类.

        不过组件类默认是不启用的.需要显式配置一下Spring,从而命令它去寻找带有@Component注解的类,并为其创建Bean,如下:

package main.java.Demo1;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * @author myvina@qq.com
 * @date 18-4-15 下午8:54
 */

@Configuration
@ComponentScan
public class CompactDiskConfig {
}

        类CompactDiskConfig通过Java代码定义了Spring的装配规则.

        使用@Configuration注解的类表示该文件是一个配置类.

        使用@ComponentScan注解表示在Spring中启用组件扫描,如果没有其他配置,会默认扫描与配置类相同的包及其子包.(也可通过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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="main.java.Demo1"/>
    
</beans>
        下面来创建一个测试类:

package main.java.Demo1;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.junit.Assert.assertNotNull;

/**
 * @author myvina@qq.com
 * @date 18-4-15 下午6:56
 */

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CompactDiskConfig.class)
public class CDPlayerTest {
    @Autowired
    private BeatlesCD cd;

    @Test
    public void cdShouldNotNull(){
        assertNotNull(cd);
    }
}
        测试结果如下:
四月 15, 2018 9:06:30 下午 org.springframework.test.context.support.DefaultTestContextBootstrapper getDefaultTestExecutionListenerClassNames
信息: Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
四月 15, 2018 9:06:30 下午 org.springframework.test.context.support.DefaultTestContextBootstrapper getTestExecutionListeners
信息: Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@2ed94a8b, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@38082d64, org.springframework.test.context.support.DirtiesContextTestExecutionListener@dfd3711, org.springframework.test.context.transaction.TransactionalTestExecutionListener@42d3bd8b, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@26ba2a48]
四月 15, 2018 9:06:31 下午 org.springframework.context.support.GenericApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.GenericApplicationContext@6cc4c815: startup date [Sun Apr 15 21:06:31 CST 2018]; root of context hierarchy

Process finished with exit code 0

        无错误,表示运行成功.



为组件扫描的Bean命名:

        @Component("name")将该组件命名为name

设置组件扫描的基础包:

        @ComponentScan("packageName")设置需要扫描的基础包

        还可设置扫描多个包:@ComponentScan(basePackages={"package1", "package2"},这样该配置类会扫描多个包:

        除了可以设置为String类型之外,还可制定包中所包含的类或接口:@ComponentScan(basePackageClasses={class1, class2}


通过为Bean添加注解实现自动装配:

package main.java.Demo1;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author myvina@qq.com
 * @date 18-4-15 下午9:16
 */

@Component
public class CDPlayer {
    private CompactDisc cd;

    @Autowired
    public CDPlayer(CompactDisc cd){
        this.cd = cd;
    }

    public void play(){
        cd.play();
    }
}

        @Autowired注解表明创建CDPlayer Bean的时候,会通过这个构造器来进行实例化并且会传入一个可设置给CompactDisc类型的Bean,该注解不仅能用在构造器上,还能用在属性的Setter方法上.


验证自动装配(紧接上一个Test):

package main.java.Demo1;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.junit.Assert.assertNotNull;

/**
 * @author myvina@qq.com
 * @date 18-4-15 下午6:56
 */

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CompactDiskConfig.class)
public class CDPlayerTest {
    @Autowired
    private BeatlesCD cd;

    @Test
    public void cdShouldNotNull(){
        assertNotNull(cd);
    }

    @Autowired
    private CDPlayer cdPlayer;

    @Test
    public void cdPlayerPlay(){
        cdPlayer.play();
    }
}

        运行结果如下:

四月 15, 2018 9:21:47 下午 org.springframework.test.context.support.DefaultTestContextBootstrapper getDefaultTestExecutionListenerClassNames
信息: Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
四月 15, 2018 9:21:47 下午 org.springframework.test.context.support.DefaultTestContextBootstrapper getTestExecutionListeners
信息: Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@38082d64, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@dfd3711, org.springframework.test.context.support.DirtiesContextTestExecutionListener@42d3bd8b, org.springframework.test.context.transaction.TransactionalTestExecutionListener@26ba2a48, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@5f2050f6]
四月 15, 2018 9:21:47 下午 org.springframework.context.support.GenericApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.GenericApplicationContext@3a82f6ef: startup date [Sun Apr 15 21:21:47 CST 2018]; root of context hierarchy
Playing Beatles

Process finished with exit code 0


以上就为Spring中自动化装配Bean的详解.

阅读更多
换一批

没有更多推荐了,返回首页