Spring的bean的装配 @Componen @ComponentScan @Autowired

Spring 配置方式

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

自动化装配bean

Srping 从2个角度来实现自动化

  • 组件扫描 ~ Spring会自动发现上下文所创建的bean
  • 自动装配 ~ Spring自动满足bean之间的依赖

Spring 启动扫描的方式

  • 采用注解扫描组件
@ComponentScan
public class Test{

}

@ComponentScan 默认会扫描与配置相类相同的包!如果Test类在com.test包中那么Spring就会扫描com.test包和它的所有子包

  • 利用XML方式配置扫描
<context:component-scan base-package="com.test" />

@ComponentScan的使用

为扫描的组件命名

采用@Component

@Component("testDemo")
public class Test{

}
//这里还有另外一种命名方式
@Named("testDmo")
public class Test{

}

设置组件扫描的基础包

  • 采用String类型表示(这种方式如果基础代码重构的话就要修改)
@Configuration
@ComponentScan(basePackages="com.test")
public class Config(){

}
//扫描多个包
@Configuration
@ComponentScan(basePackages={"com.test","com.entity"})
public class Config(){

}
  • 将扫描的basePackages指定为类或者接口 让Spring扫描指定类所在的包!
@Configuration
@ComponentScan(basePackageClasses={"Test.class","Entity.class"})
public interface Config(){

}

@Autowired的使用

  • 构造器装配
    @Component
    public class Service {
        private PayService pService;

        @Autowired
        public Service(PayService pService){
            this.pService = pService;
        }

    //在构造器加完注解后就可以使用pService了
    //(PayService必需已经扫描配置到Spring中)  
    }
  • Setter方法上

    @Component
    public class Service {
        private PayService pService;
        @Autowired
        public void SetService(PayService pService){
            this.pService = pService;
        }   
    }

在上面有@Named在一般场景可以代替@Component
这里同样可以用@Inject代替@Autowired

猜你喜欢

转载自blog.csdn.net/wolf2s/article/details/64473922