【Spring】—— 自动装配

一、Spring中装配bean的方式

1.在XML中显式配置

2.在Java中进行显式配置

3.隐士的bean发现机制和自动装配

二、自动装配示例

1.在需要装配到其他bean中的类中加入@Component注解

package study.spring.configure.auto;

import org.springframework.stereotype.Component;

/**
 * 第一步:将该类声明成一个组件类,括号内的参数为组件类的id自定义名称,也可以使用@Named.
 * spring会自动生成该类的bean
 * @author wang
 *
 */
@Component("lonelyHeartsClub")
public class SgtPeppers implements CompactDisc{

    private String titil = "Sgt. Pepper's Lonely Hearts Club Band.";
    private String artist = "The Beatles";
    
    @Override
    public void play() {
        
        System.out.println("Playing " + titil + " by " + artist);
    }

}

2.开启组件扫描

  i.使用java配置开启

package study.spring.configure.auto;

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

/*
 *    使用@ComponentScan注解开启组件扫描,设置扫描的基础包名
 *        参数basePackages
 *        或者basePackageClasses
 */

@Configuration
@ComponentScan(basePackages={"study.spring.configure.auto","study.spring.configure.auto2"})
public class CDPlayerConfig {

    
}

  ii.使用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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    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
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">
        
    
    <context:component-scan base-package="study.spring.configure.auto"></context:component-scan>
    
</beans>

3.在注入的bean中选择三种方法,使用@Autowired对bean注入

  i.在属性上直接注入

  ii.在构造方法上注入

  iii.在Set方法上注入

package study.spring.configure.auto;

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

@Component
public class CDPleayer {

    @Autowired
    private CompactDisc cd;
    
    public CompactDisc getCd() {
        return cd;
    }

    /*
     * 不同的注入方法
     * 1. set方法注入
     * 2. 构造器注入
     * 3. 属性上直接注入 
     * 
     * @Autowired与@Inject类似
     */
    
    @Autowired
    public void setCd(CompactDisc cd) {
        this.cd = cd;
    }

    @Autowired(required=false)
    public CDPleayer(CompactDisc compactDisc) {
        this.cd = compactDisc;
    }
    
    public void play(){
        cd.play();
    }
}

  注:可以在任何方法上使用@Autowired注入

三、自动注入的局限性  

  虽然自动注入很方便,但是自动注入需要自动创建bean实例,但是对于第三方的jar包中的类文件而言,不能直接使用注解进行声明为组件,因此还需要xml配置。

猜你喜欢

转载自www.cnblogs.com/bopo/p/9274455.html
今日推荐