1.准备工作:导入aop包
2.beans.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--开启注解的支持-->
<context:annotation-config/>
<!--指定要扫描的包,这个包下的注解会生效-->
<context:component-scan base-package="com.tt"/>
</beans>
3.属性注入
3.1 方式一
//@Component 组件等价于<bean id="user" class="com.tt.pojo.User"/>
@Component
//设置作用域
@Scope("singleton")
public class User {
public String name="甜甜";
public void setName(String name){
this.name = name;
}
}
3.2 方式二
//@Component 组件等价于<bean id="user" class="com.tt.pojo.User"/>
@Component
public class User {
public String name;
//@Value相当于<property name="name" value="甜甜"/>
@Value("甜甜")
public void setName(String name){
this.name = name;
}
}
拓展
@Component有几个衍生注解,我们在web开发中,会按照mvc三层架构分层
这四个注解功能都是一样的,只是为了分层表示
- dao层【@Repository】
@Repository
public interface UserDao {
}
- service层【@Service】
@Service
public interface UserService {
}
- controller层【@Controller】
@Controller
public class UserController {
}