Spring基础(一)------装配Bean

时间:2023-03-09 08:21:38
Spring基础(一)------装配Bean

一、Spring配置的可选方案

  三种主要的装配机制:

     在xml文件中进行显示配置;

     在java中进行显示配置;

     隐式的bean发现机制和自动装配。

  使用建议:尽可能使用自动配置的机制,显示配置越少越好,若必须要显式配置bean的时候,(例如有些源码并非自己维护,需要为这些代码配置bean的时候),推荐使用类型安全并且比XML更加强大的JavaConfig,

       只有当你想要使用遍历的XMl命名空间,并且在JavaConfig中同样没有实现是,才使用XML。

二、自动化装配bean

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

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

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

  CompactDisc接口在Java中定义CD的概念

 package soundsystem;

 public interface CompactDisc{
void play();
}

  

  带有@Component注解的CompactDisc实现类SgtPeppers

 package soundsystem;

 import org.springframework.stereotype.Component;

 @Component
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);
}
}

  此处实现类功能暂时不重要,重要的是 @Component注解的作用:表明该类会作为组件类,并告知Spring需要为这个类创建bean,故而不需要显式配置SgtPeppers bean。

  

  @ComponentScan注解启用了组件扫描

 package soundsystem;

 import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; @Configuration
@ComponentScan
public class CDPlayerConfig {
}

  组件扫描默认是不启用的,需要显式的配置Spring,此处通过Java代码定义了Spring的装配规则,在Spring中启用组件扫描。

  在没有其他配置下,@ComponentScan只会默认扫描与配置类相同的包。

当然,也可以用XML文件来启用组件扫描,即可以使用Spring context命名空间的<context:component-scan>元素。

  通过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="soundsystem"/>
</beans>

  2.2 为组件扫描的bean命名

    Spring应用上下文会把所有的bean都会给一个ID,尽管上文SgtPeppers bean并未明确的设置ID,但Spring会默认的设置该bean ID为sgtPeppers,但若你想把期望的ID作为值传递给@Component注解,比如将这个bean标识为lonelyHeartClub,则配置如下:

@Component("lonelyHeartsClub")
public class SgtPeppers implements CompactDisc {
...
}

    设置组件扫描的基础包:

   如果需要指定包,需要在@ComponentScan的value属性指定包名称:@ComponentScan("soundsystem");

   若想表明所设置的是基础包,可以通过basePackages属性:@ComponentScan(basePackages="soundsystem");

   basePackages可以设置多个基础包,如@ComponentScan(basePackages="soundsystem","video")

  2.3 通过为bean添加注解实现自动装配 

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

   即通过@Autowired注解在构造器之上,当然@Autowired注解不仅能够用在构造器之上,还能用在属性的Setter方法。

三、通过java代码装配bean

  3.1 创建配置类

  修改CDPlayerConfig的配置:

package soundsystem;

import org.springframework.context.annotation.Configuration;

@Configuration
public class CDPlayerConfig { }

  3.2 声明简单的bean

  在JavaConfig中申明bean,需要编写一个方法,这个方法会创建所需类型的实例,然后给这个方法添加@Bean注解,如下方代码:

@Bean
public CompactDisc sgtPeppers(){
return new SgtPeppers();
}

  @Bean 注解会告诉Spring这个方法将会返回一个对象,该对象要注册为Spring应用上下文中的bean。

  默认情况下,bean的ID与带有@Bean注解的方法名是一样的。

  也可以通过name属性指定一个不同的名字:

@Bean(name="lonelyHeartsClubBand")
public CompactDisc sgtPeppers(){
return new SgtPeppers();
}

四、通过XML装配bean

  4.1 创建XML配置规范

  在XML配置中,意味着要创建一个XML文件,并且要以<beans>元素为根。

  最简单的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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--configuration details go here-->
</beans>

  4.2 声明一个简单的<bean>

  声明CompactDisc bean:

<bean class="soundsystem.SgtPeppers"/>

  4.3 借助构造器注入初始化bean

<bean id ="cdPlayer" class ="soundsystem.CDPlayer">
<constructor-arg ref = "compactDisc"/>
</bean>

  当Spring遇到这个<bean> 元素,它会创建一个CDPlayer实例。<constructor-arg>元素会告知Spring 要将一个ID为compactDisc的bean引用传递到CDPlayer的构造器中。

  

五、导入和混合配置

  5.1 在JavaConfig中引用XML配置

  1、如果需要将两个类组合在一起,使用方式就是使用@Import注解导入另一个类,如在CDPlayerConfig类中导入CDConfig:

package soundsystem;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; @Configuration
@Import(CDConfig.class)
public class CDPlayerConfig {
@Bean
public CDPlayer cdPlayer(CompactDisc compactDisc) {
return new CDPlayer(compactDisc));
}
}

  2、或者采用一个更好的办法,也就是不在CDPlayerConfig中使用@Import,而采用一个更高级别的SoundSystemConfig,在这个类中使用@Import将两个配置类组合在一起:

package soundsystem;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; @Configuration
@Import({CDConfig.class,CDPlayerConfig.class})
public class SoundSystemConfig{ }

  3、让Spring同时加载XML配置文件以及其他基于Java的配置:

package soundsystem;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource; @Configuration
@Import(CDPlayerConfig.class)
@ImportResource("classpath:cd-config.xml")
public class SoundSystemConfig{ }

  5.2 在XML配置中引用JavaConfig

   将BlankDisc bean 拆分到自己的配置文件中,该文件名为cd-config.xml,在XML配置文件中使用<import> 元素来引用该文件:

 <?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:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <import resource="cd-config.xml"/>
<bean id="cdPlayer"
class="soundsystem.CDPlayer"
c:cd-ref = "compactDisc"/>
</beans>

   为了将JavaConfig类导入到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:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean class="soundsystem.CDConfig"/>
<bean id="cdPlayer"
class="soundsystem.CDPlayer"
c:cd-ref = "compactDisc"/>
</beans>

参考文档:《Spring实战第4版》

注:本篇学习文章的实例代码以及内容大多数来源于参考文档,仅供本人参考学习,加深理解之用,无任何商业用途,转载请与本人联系,若私自转载用于商业用途,一切后果自负。