a02-1 装配Bean-自动化装配(Spring实战)

2018-08-07  本文已影响0人  brusion

本篇内容

1、Spring在装配方式有三种:

2、自动化装配bean

一、自动化装配

1、定义接口

public interface CompactDisc {
    void play();
}

2、定义实现类

@Component
public class CDPlayer implements CompactDisc {
    public void play() {
        System.out.println("CD-Player  playing ... ... ");
    }
}

3、定义配置类

@Configuration
@ComponentScan
public class CDConfig {
}

4、测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CDConfig.class)
public class CDPlayerTest {
    @Autowired
    private CompactDisc compactDisc;
    @Test
    public void getBean() {
        compactDisc.play();
    }
}

5、为组件扫描的bean命名

5.1、使用@component
@Component("pagger")
public class CDPlayer implement CompactDisc{}
5.2、使用@Named
@Named("pagger")
public class CDPlayer implement CompactDis{}

二、设置组件扫描的基础包

@Configuration
@ComponentScan(“com.demo”)
public class CDPlayerConfig{}

1、设置多个包扫描地址:


@ComponentScan(basePackages={“com.demo.service”,“com.demo.dao”})

2、指定包中的类或接口


@ComponentScan(basePackageClasses={UserDao.class,UserService.class})


三、给bean实现自动装配

1、创建接口

public interface CompactDisc {
    void play();
}

2、创建实现类

@Component
public class SgtPepper implements CompactDisc {
    public void play() {
        System.out.println("Sgt Pepper play ... ... ");
    }
}

3、创建实现类

@Component
public class CDPlayer {
    private CompactDisc compactDisc;
    @Autowired
    public CDPlayer(CompactDisc compactDisc) {
        this.compactDisc = compactDisc;
    }
    public void play() {
        compactDisc.play();
    }
}

4、创建配置类

@Configuration
@ComponentScan
public class CDConfig {
}

5、测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CDConfig.class)
public class CDPlayerTest {
    
    @Autowired
    private CompactDisc compactDisc;
    @Autowired
    private CDPlayer cdPlayer;
    @Test
    public void showBean(){
        compactDisc.play();
    }
    @Test
    public void getBean() {
        cdPlayer.play();
    }
}

6、CDPlayer其他方式注入

    @Autowired
    public void setCompactDisc(CompactDisc compactDisc) {
        this.compactDisc = compactDisc;
    }
    @Autowired
    public void initCompactDisc(CompactDisc compactDisc) {
        this.compactDisc = compactDisc;
    }

7、注意

@Autowired(required=false)

代码地址:


https://github.com/brusion/brusion-code/tree/master/demo-java/03%20-%20demo%20-%20spring/spring-demo-study/01-di 

上一篇下一篇

猜你喜欢

热点阅读