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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值