明确差异点

无论是基于注解的配置还是基于xml文件的配置,都是为了实现IOC,降低程序中的依赖关系。
只不过两者实现的方式不一样,各有各的便利的地方。

学习内容

和基于xml文件的配置类似,我们要学习的注解有一下几种类型(和前面的内容相互照应):

  • 用于bean的创建于注册 @Component,@Controller,@Service, @Repository
  • 管理bean的作用范围 @Scope
  • 管理bean的生命周期 @PostConstruct和@PreDestroy
  • 进行bean对象的依赖注入 @Autowired,@Qualifier @Resource
  • 基本类型和String类型的依赖注入@Value
  • 对于集合类型的依赖注入不能通过注解的形式完成,需要使用xml的方式完成

我们写完注解之后,要想生效,让程序启动的时候就解析注解并进行容器的创建于注册,就需要在bean.xml文件中配置Component-scan这样的组件扫描期间,配置如下:注意 beans节点后面的xmlns的定义和之前是不同的,需要进行改变。

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <!--告知spring在创建容器时要扫描的包,配置所需要的标签不是在bean约束中,
       而是在一个名称为context的名称空间和约束中-->
    <context:component-scan base-package="com.lujuan"/>
</beans>

bean的创建

@Component(value="accountService")
@Scope("prototype")
public class AccountService implements IAccountService {
    public void saveAccount() {

        System.out.println("AccountService: saveAccount");
    }
    @PostConstruct
    public void init(){

        System.out.println("init......");
    }
    @PreDestroy
    public void destroy(){

        System.out.println("destroy......");
    }
}

在@Component注解中,其应用对象为类文件,告知spring把当前类添加到容器中进行管理。他有一个value属性,用于指定bean的id,当不配置的时候,默认使用类名称(首字母小写)作为bean id。value也可以省去,直接用Component("accountService")效果是一样的。
@Controller,@Service, @Repository这几个是继承了@Component的,作用是一样的,只不过在web的三层架构更能说明该类文件所处的位置以及作用:

  • @Controller 作用于web层的类文件
  • @Service 作用于service层的类文件
  • @Repository 作用于dao持久层的类文件

bean的作用范围

不配置时@Scope的默认值为Singleton,需要进行多例配置的时候,要使用prototype

bean的生命周期

@PostConstruct注解对应init-method这个属性值
@PreDestroy注解对应为destroy-method这个属性值

bean对象的依赖注入

@Autowired
private AccountDao ad;

@Autowired
@Qualifier(value = "ad")
private AccountDao ad;

@Resource(name = "ad")
private AccountDao ad;
  • @Autowired:
    注入规则:按照类型进行注入,当匹配结果只有一个时则注入成功。当匹配结果有多个时,按照变量名称进行匹配。当使用@Autowired注入时,可以不用写set方法。
    出现的位置:可以在变量上,也可以在方法上

  • @Qualifier
    出现的位置:可以在变量上,也可以在方法上。当出现在变量上时一定要和@Autowired一起使用。当出现在方法上时,可以不用使用@Autowired。
    属性:value,用于指明bean的id,value可省去直接指明id。

  • @Resource:
    作用:直接按照bean的id进行注入,可独立使用
    属性:name,用于指定bean的id

    基本/String类型的依赖注入

    @Value("15")
    private int age;

    @Value("lujuan")
    private String name;