注解说明
在开发中简单的配置使用注解,太过复杂的还是使用xml配置文件
-
@Autwired:自动装配通过类型,名字
-
@Nullable 字段标记了这个注解,说明这个字段可以为null;
-
@Resource:自动装配通过名字,类型
-
@Component:组件,放在类上,说明这个类被Spring管理了,就是bean!!!
(使用了@Component,getBean()的时候取的是类的小写的名字)
使用注解开发
在Spring4之后,要使用注解开发,必须要保证aop包导入
使用注解需要导入context(上下文)约束,增加注解的支持
使用@Component系列是为了创建对象,方便管理对象,@Autwired是为了赋值
1. bean
bean可以管理别人写的类,component只能管理自己写的类
2. 属性如何注入
在实行上使用注解@Value(“属性值”)
3. 衍生的注解
@Repository、@Service、@Controller加上这三个说明这个文件就被spring给托管了
实现自动装配的功能
@Component有几个衍生的注解,我们在web开发中,会按照MVC三层架构分层
- dao【@Repository】@Repository和@Component的功能是一样的,但一般在dao层用@Repository来
代替@Component - service【@Service】
- controller【@Controller】
4. 自动装配置
官方文档的bean.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:annotation-config/>
<bean class="example.SimpleMovieCatalog" primary="true">
<!-- inject any dependencies required by this bean -->
</bean>
<bean class="example.SimpleMovieCatalog">
<!-- inject any dependencies required by this bean -->
</bean>
<bean id="movieRecommender" class="example.MovieRecommender"/>
</beans>
```java
<?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="org.example"/>
</beans>
注意:
-
使用context:component-scan隐式启用 context:annotation-config.
context:annotation-config使用时通常不需要包含 元素context:component-scan。 -
此外,当您使用== component-scan 元素时,AutowiredAnnotationBeanPostProcessor和
== CommonAnnotationBeanPostProcessor都隐式包含在内。这意味着这两个组件被自动检测并连接在一起——所有这些都没有在
XML 中提供任何 bean 配置元数据。 -
您可以禁用注册 AutowiredAnnotationBeanPostProcessor并
CommonAnnotationBeanPostProcessor通过包括annotation-config与属性的值false。
在开发中简单的配置使用注解,太过复杂的还是使用xml配置文件
- @Autwired:自动装配通过类型,名字
- @Nullable 字段标记了这个注解,说明这个字段可以为null;
- @Resource:自动装配通过名字,类型
5. 作用域
@Scope 放在类上,默认是单例模式
@Scope(prototype)是原型模式,每次创建的都是一个新的对象
6. 小结
xml与注解:
- xml更加万能,适用于任何场合,维护简单方便
- 注解不是自己类使用不了,维护相对复杂
xml与注解最佳实践:
- xml用来管理bean
- 注解只负责完成属性的注入
- 我们在使用的过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支持
<!--指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-pakage="需要指定的包的名称"/>
<context:annotation-config/>