Java注解方式出来很长时间了,迟迟偷懒,对此不曾多加理会。今晚大致看了一下Spring的注解实现,果然省略不少往日Spring XML文件的编写和维护的工作。
使用注解定义Boss类,名称:boss,范围:prototype
@Component("boss")
@Scope("prototype")
public class Boss {
@Autowired
private Car car;
@Autowired
private Office office;
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
public Office getOffice() {
return office;
}
public void setOffice(Office office) {
this.office = office;
}
@Override
public String toString() {
return "car:" + car + "\n" + "office:" + office;
}
@PostConstruct
public void postConstruct1() {
System.out.println("postConstruct1");
}
@PreDestroy
public void preDestroy1() {
System.out.println("preDestroy1");
}
}
在Spring XML文件中声明如下内容:用于Spring容器从哪里扫描Bean对象(提供regex、aspectj两种表达式)
<context:component-scan base-package="ioc.annotation.example6"> <context:include-filter type="regex" expression="com\.annotation\.example6\..*" /> <context:exclude-filter type="aspectj" expression="ioc.annotation.example6.service..*" /> </context:component-scan>