使用注解开发
说明
- 在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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
1.Bean实现
1)配置扫描那些包下的注解
<context:component-scan base-package="com.xiaoguan.pojo"/>
2)在指定包下编写类,增加注解
@Component("user")
//相当于配置文件中<bean id="user" class="..."/>
public class User{
public String name = "xiaoguan";
}
3)测试
@Test
public void test(){
ApplicationContext context = new ClassPathApplicationContext("bean.xml");
User user = (User)context.getBean("user");
System.out.println(user.name);
}
2.属性注入
使用注解注入属性
1)可以不用提供set()方法,直接在直接名上添加@value(“值”)
@Component("user")
public class User{
@Value("xiaoguan")
//相当于配置文件中<property name="name" value="xiaoguan"/>
public String name;
}
2)如果提供了set方法,在set方法上添加@value(“值”);
@Component("user")
public class User{
public String name;
@Value("xiaoguan")
public void setName(String name){
this.name = name;
}
}
3.衍生注解
@Component的三个衍生注解
- @Controller:web层
- @Service:service层
- @Repository:dao层