注意:
- 在
Spring 4.0
后,要使用注解开发,必须保证aop
的包导入了。- 使用注解需要导入
context
约束,增加注解支持,javaConfig
除外。
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="org.example.pojo"/>
<context:annotation-config></context:annotation-config>
</beans>
注解
@Resource
:自动装配默认通过名字然后是类型@Autowired
:自动装配默认通过类型然后是名字@Qualifier(value="beanId")
:当@Autowired
不能唯一自动装配上属性时使用@Nullable
:字段标记了这个注解,说明这个字段可以为null
@Component
:组件,放在类上,说明这个类被Spring
管理了,就是bean
@Scope
:作用域,单例模式——@Scope("singleton")
、原型模式——@Scope("prototype")
@Value
:属性值的注入,例如@Value("值")
@Configuration
:代表这是一个配置类,就和xml
配置文件的作用是一样的。这个类也会被Spring
容器托管,注册到容器中,因为他本来就是一个@Component
@Bean
:注册一个bean
就相当于xml
配置文件中的bean
标签。注解所标注的方法名就相当于bean
标签的id
,方法的返回值就相当于bean
标签的class
属性
衍生注解
@Component
有几个衍生注解,我们在web
开发中,会按照mvc
三层架构分层!实际的作用与@Component
一致- dao ------------->
@Repository
- service---------->
@Serice
- controller------->
@Controller
- dao ------------->