Spring自动化装配-Spring实战读书笔记

定义接口

package soundsystem;
public interface CompactDisc{
      void play( );
}

定义

接口的实现

package soundsystem;
@component
public class SgtPeppers implements CompactDisc{
     private String title="lonely hearts club band";
     private String artist="The Beatles";
      public void play(){
          System.out.println("title:"+title+"artist:"+artist);
     }
}

@Component表明该类会作为组件类并告知Spring为这个类创建bean
组件扫描默认是不启动的,需要显式配置一下

package soundsystem;
@Configuration
@ComponentScan
public class CDPlayerConfig{
}


@ComponentScan会默认扫描与配置类相同的包,CDPlayerConfig位于soundsystem中,就扫描这个包和其下子包,查找带有@component标记的类
2.利用XML配置

<?xml version="1.0" encoding="UTF-8">
<beans xmlns="http://www.springframework.org/scheme/beans" 
  xmlns:xsi="http://www.w3.org/2001/XMLScheme-instance"
  xmlns:context="http://www.springframework.org/scheme/context"
  xsi:schemeLocation="http://www.springframework.org/scheme/beans
  http://www.springframework.org/scheme/beans/spring-beans.xsd
  http://www.springframework.org/scheme/context
  http://www.springframework.org/scheme/context/spring-context.xsd">

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

为bean命名
一个ID @component(“LonelyHeartsClub”) 或者 @Named(“LonelyHeartsClub” )
设置扫描的基础包 @ComponentScan(“soundsystem”) @ComponengScan(basePackages={“soundsystem”,”video”})
还可以将其指定为包中的类或者接口

@Autowired 会让Spring在上下文中寻找匹配某个bean需求的其他bean,该注解可用于构造器,Setter,类的各种方法
如果上下文没有匹配的bean,Spring会抛出异常,需要将required属性设置为false,而且还要设置null检查,设置后如果未发现匹配,会将该bean处于未装配状态

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值