Spring实战——第2章 装配Bean

第2章 装配 Bean

一、自动化配置

现在设置一个CD类和一个播放器类,CD类可以被注入到播放器类中,于是

  1. 设置一个CD类的接口
package Spring.AutoConfig;

public interface ComptonDisc {
    void play();
}
  1. 设置一个CD类
package Spring.AutoConfig;

import org.springframework.stereotype.Component;

@Component// 将这个类设置为Bean组件,等待搜索
public class HasSong implements ComptonDisc {

    @Override
    public void play() {
        String author = "王菲";
        String title = "浪迹天涯";
        System.out.println(author +"演唱"+ title);
    }
}
  1. 设置一个播放器类
package Spring.AutoConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component // 播放器类也是一个组件
public class CDPlayer implements MediaPlayer {
    private ComptonDisc cd;
    
    @Autowired// 自动装配,此时spring将在此处自动注入ComptonDisc类的对象
    public CDPlayer(ComptonDisc cd) {
        this.cd = cd;
    }

    @Override
    public void play() {
        cd.play();
    }
}
  1. 设置一个配置类
package Spring.AutoConfig;

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

@Configuration// 声明这是一个配置类,由此开始启动
@ComponentScan // spring将开始搜索所有组件,并将其装配起来
public class CDPlayerConfig {
}

1. @ComponentScan

如果没有其他配置的话,@ComponentScan会默认扫描与配置类相同的包,因为该配置类位于AutoConfig包中,所以会扫描该包下的所有子包,查找带有@Component的类。

如果想要使用XML文件实现组件扫描,如下

<context:component-scan base-package="AutoConfig"/>

@ComponentScan还可以指定扫描的包如@ComponentScan(basePackages="AutoConfig, "videos")

@ComponentScan(basePackages = {"AutoConfig", "videos"})// 指定多个默认扫描包
@ComponentScan(basePackageClasses = {CDPlayer.class, DVDPlayer.class})// 使用类指定默认扫描包
public class CDPlayerConfig {
}

也可以使用

2. @Component

修改名称

例如将CD类名称改为loveSong

@Component("loveSong")
public class hasSong implements CompactDisc{}

@Named // 作用等同于Component
public class hasSong implements CompactDisc{}

3. @Autowired

其不仅可以用在构造方法上,也可以用在setter方法上

@Autowired(required = false)// 如果没有可以匹配的Bean,这个设置可以不报错
@Inject// 该注解大多数时候可以与autowired互换
public CDPlayer(ComptonDisc cd) {
    this.cd = cd;
}

如果有且只有一个Bean被扫描到,则会直接装配,但如果有多个符合依赖关系的Bean,需要特别指定

二、使用java配置

package Spring.JavaConfig;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CDPlayerConfig {
    @Bean //注入,选择一个实例注入到CDPlayer中
    public CDPlayer cdPlayer(@Qualifier("randomSetCD") ComptonDisc comptonDisc){
        return new CDPlayer(comptonDisc);
    }

    @Bean
    public ComptonDisc song1(){
        return new Song1();
    }

    @Bean
    public ComptonDisc song2(){
        return new Song2();
    }

    @Bean // 自定义一个类,spring会接受return的new 实例类,并将其设置为一个Bean
    public ComptonDisc randomSetCD() {
        double choice = Math.random();
        if (choice>0.5){
            return new Song1();
        } else {
            return new Song2();
        }
    }
}
package Spring.AutoConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

//删除Component组件
public class CDPlayer implements MediaPlayer {
    private ComptonDisc cd;
    // 此时也应该指定自动装配注解
    @Autowired// 自动装配,此时spring将在此处自动注入ComptonDisc类的对象
    public CDPlayer(ComptonDisc cd) {
        this.cd = cd;
    }

    @Override
    public void play() {
        cd.play();
    }
}

三、使用xml配置

1. 构造方法注入

使用一个待列表的参数类

package soundsystem.collections;

import java.util.List;

import soundsystem.CompactDisc;

public class BlankDisc implements CompactDisc {

  private String title;
  private String artist;
  private List<String> tracks;

  public BlankDisc(String title, String artist, List<String> tracks) {
    this.title = title;
    this.artist = artist;
    this.tracks = tracks;
  }

  public void play() {
    System.out.println("Playing " + title + " by " + artist);
    for (String track : tracks) {
      System.out.println("-Track: " + track);
    }
  }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:c="http://www.springframework.org/schema/c"
       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">
    <!--    构造参数添加方式-->
    <bean id="song1" class="Spring.XMLConfig.Song1">
        <constructor-arg value="ti"/>
        <constructor-arg value="er"/>
    </bean>
    <!--    c命名空间添加方式-->
    <bean id="song2" class="Spring.XMLConfig.Song1" c:_0="se" c:_1="sef"/>
    <bean id="song3" class="Spring.XMLConfig.Song1" c:title="se" c:author="sef"/>
</beans>

添加list参数

<?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">
    <bean class="Spring.MixedConfig.Congif.JavaConfig"/>
    <bean id="blankDisc" class="Spring.MixedConfig.BlankDisc">
        <constructor-arg value="浮躁"/> value表示字面值,按照顺序添加参数内容
        <constructor-arg value="王菲"/>
        <constructor-arg>
            <list> list参数内容
                <value>121</value>
                <value>aesg</value>
            </list>
        </constructor-arg>
    </bean>
</beans>

2. setter方法注入

如果使用setter方法添加的参数

// setter方法内容如下
package Spring.XMLConfig;

import org.springframework.beans.factory.annotation.Autowired;

public class CDPlayer implements MediaPlayer {
    private ComptonDisc cd;
    
    @Autowired
    public void setCd(ComptonDisc cd){
        this.cd = cd;
    }

    public void play() {
        cd.play();
    }
}

则xml文件配置如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:p="http://www.springframework.org/schema/p"
       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">
    <bean id="blankDisc" class="Spring.XMLConfig.BlankDisc" c:_0="浮躁" c:_1="王菲">
        <constructor-arg>
            <list>
                <value>aneoig</value>
                <value>asefesag</value>
                <value>asefesga</value>
            </list>
        </constructor-arg>
    </bean>
<!--    property是向带有@Autowired的普通方法注入参数的命令-->
    <bean id="cdPlayer" class="Spring.XMLConfig.CDPlayer">
        <property name="cd" ref="blankDisc"/>
    </bean>
<!--    此外,也可以使用p命令空间,cd为实参名,ref表示注入类型为blankDisc类-->
    <bean id="cdPlayer1" class="Spring.XMLConfig.CDPlayer" p:cd-ref="blankDisc"/>
</beans>
package Spring.XMLConfig;

import java.util.List;

public class BlankDisc implements ComptonDisc {
    private String title;
    private String author;
    private List<String> tracks;

    public void setAuthor(String author) {
        this.author = author;
    }

    public void setTitle(String title) {
        this.title = title;
    }
    public void setTracks(List<String> tracks) {
        this.tracks = tracks;
    }

    @Override
    public void play() {
        System.out.println(this.author+"演唱专辑"+this.title);
        for (String i: tracks){
            System.out.println("音轨为第" + i);
        }
    }
}

如果想要装配集合,则需要使用util-list参数

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p"
       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">

<!--使用util:list方法指定列表-->
    <util:list id="tracklist">
        <value>anseiofn</value>
        <value>saefesf</value>
        <value>sfesfes</value>
    </util:list>
<!--将声明的list添加到blankDisc中-->
    <bean id="blankDisc" class="Spring.XMLConfig.BlankDisc" p:title="浮躁" p:author="王菲"
          p:tracks-ref="tracklist"/>
</beans>

四、混合配置

1. xml中导入javaConfig和xml类

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:c="http://www.springframework.org/schema/c"
       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">
    <!--导入xml文件-->
    <import resource="CDPlayerConfig.xml"/>
    <!--导入javaConfig文件-->
    <bean class="Spring.MixedConfig.Congif.JavaConfig"/>
	<!--id表示别名,class表示类的位置-->
    <bean id="specissue" class="Spring.MixedConfig.SpecIssue" c:_0="tit" c:_1="sae"/>
    <bean id="cdPlayer2" class="Spring.MixedConfig.CDPlayer">
        <!--使用构造方法导入依赖,ref表示依赖的bean名-->
        <constructor-arg ref="specissue"/>
    </bean>
</beans>

2. javaConfig中导入java类和xml类

package Spring.MixedConfig.Congif;

import Spring.MixedConfig.CDPlayer;
import Spring.MixedConfig.ComponDisc;
import Spring.MixedConfig.SpecIssue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;

@Configuration
@ImportResource("classpath:BlankConfig.xml") // 导入xml文件
@Import(JavaConfig.class)// 导入java配置类
public class JavaConfig {
    private ComponDisc cd;
    @Bean
    public SpecIssue specIssue(){
        return new SpecIssue("王菲","浮躁");
    }
    @Bean
    public CDPlayer cdPlayer(){
        return new CDPlayer(cd);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值