基于 Java 的 bean 配置

来源:互联网 发布:java并发编程实战手册 编辑:程序博客网 时间:2024/05/21 17:37

一、声明
本测试没有使用任何xml代码
主要分 Dao、Service 层来写
为了容易阅读,文件名也相当清晰

这里写图片描述

二、代码

①DaoInterface

package test;public interface DaoInterface {    void showDAO();}

②DaoImplements

package test;import org.springframework.stereotype.Component;@Componentpublic class DaoImplements implements DaoInterface {    @Override    public void showDAO() {        System.out.println("DAO is playing Spring now");    }}

③ServiceInterface

package test;public interface ServiceInterface {    void showService();}

④ServiceImplements

package test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;@Componentpublic class ServiceImplements implements ServiceInterface {    private DaoInterface mi;    @Autowired    public ServiceImplements(DaoInterface mi) {        this.mi = mi;    }    @Override    public void showService() {        System.out.println("Service begin");        mi.showDAO();        System.out.println("Service end");    }}

⑤JavaConfiguration java配置取代xml配置

package test;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;@Configuration@ComponentScanpublic class JavaConfiguration {}

⑥SpringTest 测试类

package test;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = JavaConfiguration.class)public class SpringTest {    // @Autowired //①变量上面可以放@Autowired    private ServiceInterface service;    @Autowired // ②setter上面也可以放@Autowired    public void setService(ServiceInterface service) {        this.service = service;    }    @Test    public void test() {        service.showService();    }}

这里写图片描述

原创粉丝点击