spring学习笔记——注解
##配置文件applicationContext.xml模板
```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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/context/spring-aop.xsd">
</beans>
```
##测试类模板
@Test
public void aa(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
context.getBean("");
}
##常用依赖
```xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
```
##注解说明
<context:annotation-config/> 开启注解支持
-@Autowired :自动装配通过类型,名字
如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value ="xxx")去配置@Autowired的使用,指定一个唯一的bean对象注入
-@Resource :自动装配通过名字,类型
-@Nullable :字段标记了这个注解,说明这个字段可以为null
-@Component:组件,放在类上,说明这个类被spring管理了,就是bean
-@Value() :括号里面为值,一般放在属性上或者set方法上,给其赋值,属性的注入
-@Component :有几个衍生注解,在web开发中,会按照MVC三层架构分层
dao【@Repository】
service【@service】
controller【@Controller】
这四个注解功能都是一样的,仅名字不同,都是代表将某个类注册到spring容器中装配
-Scope() :作用域的配置 单例模式Scope("singleton")、原型模式Scope("prototype")
##Spring注解开发
在spring4之后,要使用注解开发,必须要保证aop的包导入了
使用主角需要导入context约束,注解的支持
##小结
xml与注解:
xml更加万能,适用于任何场合,维护简单方便
注解 不是自己的类使用不了,维护相对复杂
xml与注解最佳实践:
xml用来管理bean
注解只负责属性的注入