码迷,mamicode.com
首页 > 编程语言 > 详细

Spring装配bean--01组件扫描和自动装配

时间:2017-05-12 00:05:41      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:www   text   容器   base   play   配置方法   XML   void   out   

Spring容器负责创建应用程序中的bean并通过DI来协调这些对象之间的关系

Spring提供了三种主要的装配机制:

  •     在XML中进行显式配置
  •     在Java中进行显式配置
  •     隐式的bean发现机制和自动装配



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

  1. 组件扫描(component scanning):Spring 会自动发现应用上下文中所创建的bean
  2. 自动装配(autowired):Spring自动满足bean之间的依赖@Autowired

开启组件扫描的2种方法:

  • XML中配置<context:component-scan base-package="autowired" />
  • java配置类中添加@ComponentScan

以下是代码解释

1. CD光盘类

@Component("cd1")//括号内给该bean设置ID,若不设置则默认为类名首字母小写即cD
public class CD 
{
    private String title = "最炫民族风";
    private String artist = "凤凰传奇";
    
    public void play()
    {
    	System.out.println("当前播放: " + title + " 演唱者: " + artist);
    }
}

2  CDplayer播放器类

@Component("cdPlayer")
public class CDplayer 
{
    @Autowired
    private CD cd;
    
    public void play()
    {
    	cd.play();
    }
}

3  Java配置类开启组件扫描

@Configuration//声明该类是一个java配置类,不存在任何逻辑
@ComponentScan//在不声明basePackage的情况下,默认该类所在包下开启组件扫描
public class JavaConfig 
{
    
}

4 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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
        
        <context:component-scan base-package="autowired" />
</beans>

5 测试类

public class TestCase 
{
    @Test
    public void test01()
    {
    	//java配置方法  开启组件扫描
    	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(JavaConfig.class);
    	CD cd1 = (CD) context.getBean("cd1");
    	System.out.println(cd1);
    	CDplayer cp1 = (CDplayer) context.getBean("cdPlayer");
    	cp1.play();
    }
    
    @Test
    public void test02()
    {
    	//XML配置方式  开启组件扫描
    	ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    	CD cd1 = (CD) context.getBean("cd1");
    	System.out.println(cd1);
    	CDplayer cp1 = (CDplayer) context.getBean("cdPlayer");
    	cp1.play();
    }
}



  

6 console控制台结果

    autowired.CD@105fece7
    当前播放: 最炫民族风 演唱者: 凤凰传奇

Spring装配bean--01组件扫描和自动装配

标签:www   text   容器   base   play   配置方法   XML   void   out   

原文地址:http://www.cnblogs.com/dsying/p/6842904.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!