使用注解开发
-
使用注解所需要的包: org.springframework:spring-aop:5.2.2.RELEASE
-
添加注解的支持
<?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/> </beans>
-
bean
//放在类上,等价于注册了<bean id="user" class="cn.pinked.pojo.User"/> @Component public class User { public String name; }
-
属性的注入
//相当于<property name="name" value="大头儿子"/> @Value("大头儿子") public void setName(String name) { this.name = name; }
-
衍生的注解
@Component有几个衍生注解,在web开发中,会按照mvc三层架构分层
- dao -- @Repository
- service -- @Service
- controller -- @Controller
它们的功能都是一样的
-
自动装配
@Autowired
-
作用域
@Scope("")
-
小结
xml与注解
- xml更加万能,适用于任何场合,维护方便
- 注解不是自己的类使用不了,维护相对复杂
最佳实践:
- xml负责管理bean
- 注解负责属性的注入