【Spring】学习笔记06 —— 使用注解开发

1. 前提准备工作

在 Spring4 之后,要使用注解开发,必须保证 aop 包导入成功。
在这里插入图片描述
applicationContext,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"
    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">

    <!-- 指定要扫描的包,这个包下的注解就会生效-->
    <context:component-scan base-package="*"/>

</beans>

2. 常见注解使用

Bean

以下4个注解的功能是一样的,都是代表将某个类注册到 Spring 容器中,装配 Bean:

  • pojo包:@Compontent
  • dao包:@Repository
  • service包:@Service
  • controller包:@Controller

属性注入

可以在成员变量或者 set 方法上添加 @Value("值")

自动装配

  • @Autowired:自动装配,默认方式为 byType
  • @Resource:自动装配。默认方式为 byName

作用域

@scope

  • singleton:默认的,Spring 会采用单例模式创建这个对象。关闭工厂 ,所有的对象都会销毁。
  • prototype:多例模式。关闭工厂,所有的对象不会销毁。内部的垃圾回收机制会回收。

小结

XML 与 注解:

  • XML 可以适用任何场景 ,结构清晰,维护方便;
  • 注解开发简单方便,维护相对复杂;

XML与注解的最佳实践:

  • xml 用来管理 Bean;
  • 注解只负责完成属性的注入;

3. Spring 配置项说明

<context:annotation-config/>的作用是显式地向 Spring 容器注册以下4个BeanPostProcessor,以便容器能够识别相应的注解:

  • AutowiredAnnotationBeanPostProcessor
    • @Autowired
  • CommonAnnotationBeanPostProcessor
    • @ Resource
    • @ PostConstruct
    • @ PreDestroy
  • PersistenceAnnotationBeanPostProcessor
    • @PersistenceContext
  • RequiredAnnotationBeanPostProcessor
    • @Required

不过,我们使用注解一般都会配置扫描包路径选项:

<context:component-scan base-package="xxx.xxx"/>

该配置项其实也包含了自动注入上述 processor 的功能,因此当使用 <context:component-scan/>后,就可以将<context:annotation-config/> 移除了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值