Spring @Resource实例

来源:互联网 发布:python控制继电器 编辑:程序博客网 时间:2024/05/22 04:28

配置文件:

<?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;@Repositorypublic 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;@Servicepublic class JsrService {    /**     * 两种方法:成员变量,set方法     *两种方法 默认的bean id为:类首字母小写     *      *///@Resource()private JsrDao jsrDao;@Resourcepublic void setJsrDao(JsrDao jsrDAO) {this.jsrDao = jsrDAO;}@PostConstructpublic void init() {System.out.println("JsrServie init.");}@PreDestroypublic 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(); }}

工具类:点击打开链接