spring-装配bean

1.spring配置的可选方案

spring提供了三种装配bean的机制:

  • 在xml中显式配置
  • 在java中进行显式配置
  • 隐式的bean发现机制和自动转配

三种方式在适当的场合使用,当然你可以选择自己喜欢的方式转配bean。

2.自动化装配bean

  spring从两个角度实现自动化装配

  • 组件扫描(component scanning)spring会自动发现上下文中所创建的bean
  • 自动装配(autowiring):依赖注入DI

2.1 创建可被发现的bean

定义接口  CompactDisc

public interface CompactDisc {
    void play();
}

 

带有@Component注解实现类:

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

  使用@Component注解来告诉spring将该类当做组件类,并告诉spring要为这个类创建bean。这里就不要显示配置SgtPeppers的bean了。

  不过组件扫描默认是不启动的。还需要显示配置一下spring,从而命令它寻找带有@Component注解的类,并为之创建bean。

  接下来就要创建扫描组件的配置文件了,有两种方式:

  •  通过加载java配置文件,装配bean
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
//扫描注解包,装配bean
@ComponentScan(basePackages = {"cn.getword.b_beans"})
//不扫描包,也可以通过@Bean装配bean
public class CDPlayerConfig {
    @Bean
    public CompactDisc sgtPeppers(){
        return new SgtPeppers();
    }
}

 

  注意:如果仅仅使用@ComponentScan的话,默认会扫描与配置类相同的包。

  • 通过加载xml配置文件,装配bean
    <?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" xmlns:c="http://www.springframework.org/schema/c"
           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"
    > <!--通过扫描基础包,自动装配bean--> <context:component-scan base-package="cn.getword.b_beans" /> </beans>

     

测试

@RunWith(SpringJUnit4ClassRunner.class)
//通过加载xml配置文件,装配bean
@ContextConfiguration(locations = "classpath:cn/getword/b_beans/CDPlayer.xml")
//通过加载java配置文件,装配bean
//@ContextConfiguration(classes = CDPlayerConfig.class)
public class BeansTest {
    //CompactDisc接口有多个实现类,必须指明id;如果变量名和id一致,也可以匹配
//    @Qualifier("sgtPeppers")
    @Autowired
    private CompactDisc sgtPeppers;

    @Autowired
    private CompactDisc blankDisc;

    @Test
    public void play(){
        sgtPeppers.play();
        blankDisc.play();
    }
}

 

 

2.2 为组件扫描的bean命名【id】

  在前面的例子中,尽管没有明确的设置id,但是spring会根据类名为其指定一个id。SgtPeppers ->sgtPeppers

  手动设置id:

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

 

2.3 为装配的bean添加依赖注入

  使用@Autowired注解。可以放在属性前或setter方法前。

 

3.通过xml装配bean 

3.1 声明一个简单的bean:

 

posted @ 2018-09-03 16:23  fight139  阅读(120)  评论(0编辑  收藏  举报