1.@Component(注册bean)
在Spring4之后,要使用注解开发,必须要保证导入aop的包
使用注解就要导入context约束,增加注解的支持
<?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>
这里再添一个约束,用来让spring扫描指定路径下的包,这样就可以让spring自动创建bean
<!--指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="com.sun.pojo"/>
上面约束对应的注解,@Component,把这个类注册到Spring中(也就是让Spring为其生成一个bean来托管)
@Component
public class User {
public String name = "小明";
}
2.衍生的注解
@Component有几个衍生的注解,我们在web开发中,会按照mvc三层架构分层
- dao 【@Repository】
- service 【@Service】
- controller 【@Controller】
上面三个注解和@Component一样,都代表将这个类注册到Spring中,装配bean
3.@Autowired(自动装配)
该注解在我下面这个博客有详细介绍
4.@Value(属性注入)
该注解相当于是:
<property name="name" value="小明"/>
public class User {
@Value("小明")
public String name;
}