导入所需依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.7</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
</dependencies>
<?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"
xmlns:aop = "http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
">
<!-- 指定要扫描的包-->
<context:component-scan base-package="grandzio.pojos"/>
<context:annotation-config></context:annotation-config>
</beans>
@Nullable 字段标记了这个注释,表示这个字段可以为null
@Component :组件,放在类上,表示这个类被spring管理了,就是bean
@Component
public class Users {
public String name = "网际网";
//相当于<property name="id" value= "1001111"/>
@Value("1001111")
public String id;
}
衍生的注解:
@Component有几个衍生的注解在web开发中会按照mvc三层架构层
dao @Repository
service @Service
controller @Controller
此四个注解功能相同
@Scope标注模式
结论:
- xml配置万能,适用于任何场所,维护简单
- 注解 ,不是自己的类无法使用,维护相对复杂!
xml与注解的最佳实践:
- xml用来管理bean
- 注解只负责属性注入
- 在使用过程中,只需注意一个问题,必须让注解生效,需要开启注解的支持
<context:component-scan base-package="grandzio"/>
<context:annotation-config></context:annotation-config>