Spring中定义了一系列Aware接口,可用于感知spring container,获取container中的信息,bean的信息。
例如 ApplicationContextAware可以获取object所在的ApplicationContext,BeanNameAware可用于获取object所在bean的名称。
public class Cat implements ApplicationContextAware,BeanNameAware{
private Card card;
private ApplicationContext context;
// other methods ...
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
@Override
public void setBeanName(String name) {
System.out.println("Bean name is " + name);
}
}
AbstractApplicationContext context = new ClassPathXmlApplicationContext("SpringConfig.xml");
context.registerShutdownHook();
(2)Cat 实现 InitializingBean,DisposableBean
public class Cat implements InitializingBean{...}
或者 自定义函数 并在xml中添加 init-method/destroy-method 指向自定义的函数名。
// Cat.java 添加方法
public void myInit() {
System.out.println("This is my init method");
}
// xml
Bean实例化前后,添加自定义操作
新建Display.java
// Display.java
public class Display implements BeanPostProcessor{
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("Before Bean "+beanName+" init...");
return null;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("Bean "+beanName+" finished...");
return null;
}
}
// xml 添加
如果需要在BeanFactory 初始化前操作,使用BeanFactorPostProcessory用法与上面的类似。
@AutoWired: 按名字注入
@Qulifier(“relatedCard”) xml中找寻qulifier标签中value是relatedCard的
@Resource(name=“card”) xml找bean id=card的注入
public class Cat{
private Card card;
public void sound() {
System.out.println(this.card.toString()+" sound: Meow Meow Meow");
}
// setters and getters
public Card getCard() {
return card;
}
@Autowired
public void setCard(Card card) {
this.card = card;
}
public void myInit() {
System.out.println("This is my init method");
}
}
// xml
之前的xml中每个bean都有对应的标签,这个实在很麻烦,spring提供了Component annotation可以标志一个类属于Spring Container
// Cat.java
@Component
public class Cat{
private Card card;
public void sound() {
System.out.println(this.card.toString()+" sound: Meow Meow Meow");
}
// setters and getters
public Card getCard() {
return card;
}
@Autowired
public void setCard(Card card) {
this.card = card;
}
@PostConstruct
public void myInit() {
System.out.println("This is my init method");
}
@PreDestroy
public void myDestory() {
System.out.println("This is my destory");
}
}
// xml
除了@Component 之外 @Repository、@Service、@Controller 都可起到同样的效果。由于Spring会把@Repository标志的类封装成Spring 数据访问异常类型,因此只能用于Dao层。其他几个与Component意义不同,但作用一致。
@Component 泛化,都可用
@Repository 只可Dao层
@Service 业务层,但是目前该功能与 @Component 相同
@Controller 控制层,但是目前该功能与 @Component 相同
// mymessage.properties
greeting=Hello
//sound.java
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("SpringConfig.xml");
String text = context.getMessage("greeting", null,"Defaule Message", null);
System.out.println(text);
}
// xml
mymessages