1、前提准备(Spring4.x以后)
(1)导入spring-aop的依赖
(2)加入Context约束,增加注解的支持,以及加入扫描的路径配置
<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
http://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/>
<context:component-scan base-package="com.tc"/>
</beans>
2、 注解详解
2.1 Bean注入 —— @Component(“user”)
定义Bean,向Spring的IOC容器注入Bean对象,等价于:
<bean id="user" class="com.tc.entity.User"/>
@Component 也可以不指定名,在获取bean对象时使用按类型获取的方式
BeanDao bean = context.getBean(BeanDao.class);
import org.springframework.stereotype.Component;
@Component
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void print(){
System.out.println("打印user");
}
}
注:为了代码层次清晰,根据MVC设计模式,衍生出对应的3个注解,功能完全一致,名称不同而已
- @Repository:该注解用于数据访问层的bean定义,数据访问层也就是我们常写的dao层、mapper层。
@Repository("beanDao")
// @Repository
public class BeanDaoImpl implements BeanDao {
public void save() {
System.out.println("beanDao save...");
}
}
- @Service:该注解用于业务逻辑层的bean定义,即service层。
@Service("beanService")
// @Service
public class BeanServiceImpl implements BeanService {
public void save() {
System.out.println("bean service save...");
}
}
- @Controller:该注解用于表现层,控制层的bean定义,即controlle层
@Controller("beanController")
// @Controller
public class BeanController {
}
2.2 属性值注入 —— @Value
向Bean的属性注入值,相当于
<bean id="user" class="com.tc.entity.User">
<property name="name" value="jack"/>
</bean>
@Component
public class User {
@Value("jack")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void print(){
System.out.println(name);
}
}
2.3 自动装配 —— @Autowire,@Resource
详见spring—— 2.IOC章节
2.4 作用域 —— @Scope
@Component
@Scope("singleton")
public class User {
@Value("jack")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void print(){
System.out.println(name);
}
}