<?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:component-scan base-package="package com.JSR;"></context:component-scan>
</beans>
-----------------------------------
package com.JSR;
import org.springframework.stereotype.Repository;
@Repository
public class JsrDao {
public void save(){
System.out.println("this is DAO");
}
}
---------------------------------
package com.JSR;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
//@Service
@Named
public class JsrService {
/**
* 两种方法:成员变量,set方法
*两种方法 默认的bean id为:类首字母小写
*
*/
// @Inject
private JsrDao jsrDao;
@Inject
//若有JsrDao为接口的两个实现类同时注入到同一个IOC容器中指定哪一个具体的实现类注入
public void setJsrDao(@Named("jsrDao") JsrDao jsrDAO) {
this.jsrDao = jsrDAO;
}
@PostConstruct
public void init() {
System.out.println("JsrServie init.");
}
@PreDestroy
public void destroy() {
System.out.println("JsrServie destroy.");
}
public void save() {
jsrDao.save();
}
}
package com.JSR;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
//@Service
@Named
public class JsrService {
/**
* 两种方法:成员变量,set方法
*两种方法 默认的bean id为:类首字母小写
*
*/
// @Inject
private JsrDao jsrDao;
@Inject
//若有JsrDao为接口的两个实现类同时注入到同一个IOC容器中指定哪一个具体的实现类注入
public void setJsrDao(@Named("jsrDao") JsrDao jsrDAO) {
this.jsrDao = jsrDAO;
}
@PostConstruct
public void init() {
System.out.println("JsrServie init.");
}
@PreDestroy
public void destroy() {
System.out.println("JsrServie destroy.");
}
public void save() {
jsrDao.save();
}
}
----------------------------------------
工具类:UnitTestBase
package com.JSR;
import org.junit.Test;
import com.imooc.test.base.UnitTestBase;
public class TestJsr extends UnitTestBase{
public TestJsr(){
super("classpath*:spring-beanannotation5.xml");
}
@Test
public void test(){
JsrService service =super.getBean("jsrService");
service.save();
}
}
结果:
JsrServie init.
this is DAO
2017-6-5 10:30:04 org.springframework.context.support.AbstractApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@58a17083: startup date [Mon Jun 05 10:30:03 CST 2017]; root of context hierarchy
JsrServie destroy.