前言
我们在xml中配置一个bean要写一大串
<bean id="user" class="com.pojo.User"></bean>
如果我们通过注解的方式,直接在需要配置的地方写一下这样岂不是方便很多
可以看一个例子
package com.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
//等价于<bean id="user" class="com.pojo.User"></bean>
@Component
@Scope("prototype")
public class User {
@Value("dong")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- @Component就是产生一个bean
- @Scope(“prototype”)指定作用域
- @Value(“dong”)给属性填充值
需要在xml中打开的注解配置
<!--指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="com.kuang"/>
<!--开启注解的支持 -->
<context:annotation-config/>
- 指定扫描的包,这个包下的注解就会生效
- 开启注解的支持
mvc三层的一些衍生注解
dao 【@Repository】
service 【@Service】
controller 【@Controller】
他们本质都是一个Component,但是这样写可以对架构分层更加清晰
其他的一些注解复习
- @Autowired:自动装配通过类型,名字。如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value = “xxx”)去配置。
- @Nullable 字段标记了了这个注解,说明这个字段可以为null;
- @Resource:自动装配通过名字,类型。
总结
注解就是让配置更加方便