配置文件:
<?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>
Dao类:
package com.JSR;
import org.springframework.stereotype.Repository;
@Repository
public class JsrDao {
public void save(){
System.out.println("this is DAO");
}
}
Service类:
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
public class JsrService {
/**
* 两种方法:成员变量,set方法
*两种方法 默认的bean id为:类首字母小写
*
*/
// @Resource()
private JsrDao jsrDao;
@Resource
public void setJsrDao(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 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();
}
}
工具类: 点击打开链接