初探IOC注解开发
一、在spring4之后,想要使用注解形式,必须得要引入aop的包,并在配置文件当中引入一个context约束
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
二、配置注解扫描,哪个包下面的类型通过注解去扫描
<context:component-scan base-package="pers.liuchengyin.demo1"/>
三、在类上添加注解,使用注解注入属性
①不提供set方法,直接在属性名上面添加@value("值")
@Component("user")
public class User {
@Value("柳成荫")
public String name;
}
②提供set方法,在set方法上面添加@value("值")
@Component("user")
public class User {
public String name;
@Value("柳成荫")
public void setName(String name) {
this.name = name;
}
}
注解使用
一、类注解
@Component
修改一个类,将这个类交给Spring管理 相当于在配置文件当中配置<bean id="" class="">
@Component三个衍生注解
为了更好的进行分层,Spring可以使用其它三个注解,功能类似
@Controller web层
@Service service层
@Repository dao层
二、属性注入
@Value 设置普通类型的属性值
@Value("柳成荫")
public void setName(String name) {
this.name = name;
}
@Autowired 设置对象类型的属性值
使用这种方式,是按照类型完全进行属性注入,不需要在注解上使用id名称
// 这个id没有用上
@Component("dog")
public class Dog {
@Value("哈士奇")
public String name;
}
@Controller("user")
public class User {
public String name;
// 直接注入
@Autowired
public Dog dog;
@Value("柳成荫")
public void setName(String name) {
this.name = name;
}
}
习惯上是按照名称完成属性注入,必须让@Autowired注解与@Qualifier一起使用
@Autowired // 根据类型
@Qualifier("dog") // 根据名称
public Dog dog;
单独可以使用@Reource来代替
@Resource(name="dog")
public Dog dog;
使用@PostConstruct 标记初始化方法,@PreDestroy 标记销毁方法
@PostConstruct
public void init(){
System.out.println("User初始化");
}
@PreDestroy
public void destroy(){
System.out.println("User销毁");
}
使用@scope标记作用范围
XML方式和注解方式比较
XML可以适用任何场景 ,结构清晰,维护方便
注解不是自己提供的类使用不了,开发简单方便
XML与注解整合开发
让XML管理Bean,注解完成属性注入
使用过程中, 可以不用扫描,扫描是为了类上的注解在没有扫描的情况下, 使用属性注解@Resource @Value @Autowired @Qulifier
<context:annotation-config/>
示例:
<context:annotation-config/>
<bean id="person" class="pers.liuchengyin.demo1.Person"></bean>
public class Person {
@Value("柳成荫")
public String name;
}
public void test(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Person person = (Person) applicationContext.getBean("person");
System.out.println(person.name);
}