Spring随笔-bean装配

Spring提供了三种装配方式
  1.XML文件进行显式装配
  2.java中进行显示装配
  3.自动化装配
1.自动化装配的两种实现方式
  1.组件扫描:Spring会自动发现应用上下文中创建的bean
  2.自动装配:Spring自动满足bean之间的依赖
装配方式

  组件扫描

  创建可被发现的类

    类上@Component注解

    

package soundsystem;
import org.springframework.stereotype.Component;

/*Spring默认的bean id为类名首字母小写,在此处你可以自定义,也可以使用JDI提供的@Name注解为bean设置id*/ @Component("whateverYouWant")  
public class SgtPeppers implements CompactDisc { private String title = "Sgt. Pepper's Lonely Hearts Club Band"; private String artist = "The Beatles"; public void play() { System.out.println("Playing " + title + " by " + artist); } }

    @ComponentScan注解启用了组件扫描 

    @Configuration注解表明这个类是一个配置类,该类应该包含在Spring应用上下文中如何创建bean的细节。

  

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

@Configuration
@ComponentScan(bacePackages = "soundsystem")
public class CDPlayerConfig { 
}

    @ComponentScan默认会扫描与配置类相同的包。因为CDPlayerConfig类位于soundsystem包中,因此Spring将会扫描这个包以及这个包下的所有子包,查找带有@Component注解的类。这样的话,就能发现CompactDisc,并且会在Spring中自动为其创建一个bean。

    如果你更倾向于使用XML来启用组件扫描的话,那么可以使用Spring context命名空间的<context:component-scan>元素。程序清单2.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:context="http://www.springframework.org/schema/context"
  xmlns:c="http://www.springframework.org/schema/c"
  xmlns:p="http://www.springframework.org/schema/p"
  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="soundsystem" />

</beans>

 设置扫描基础包

  按照默认规则,@ComponentScan会以配置类所在的包作为基础包(basepackage)来扫描组件。如欲把配置类放在单独的包中,可在@ComponentScan后加value属性如上面代码所示。还可以通过bacePackages属性明确地表示你所设置的包是基础包。bacePackages可设置多个。

  

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

@Configuration
@ComponentScan(bacePackages = {"soundsystem","audio"})
public class CDPlayerConfig { 
}
原文地址:https://www.cnblogs.com/castielangel/p/7058805.html