编程语言
首页 > 编程语言> > 吴裕雄--天生自然--SPRING--Spring java配置

吴裕雄--天生自然--SPRING--Spring java配置

作者:互联网

package dao;

//此处没有使用@Repository声明Bean
public class TestDao {
    public void save() {
        System.out.println("TestDao save");
    }

}
package service;

import dao.TestDao;

//此处没有使用@Service声明Bean
public class TestService {
    // 此处没有使用@Autowired注入testDao
    TestDao testDao;

    public void setTestDao(TestDao testDao) {
        this.testDao = testDao;
    }

    public void save() {
        testDao.save();
    }

}
package controller;

import service.TestService;

//此处没有使用@Controller声明Bean
public class TestController {
    // 此处没有使用@Autowired注入testService
    TestService testService;

    public void setTestService(TestService testService) {
        this.testService = testService;
    }

    public void save() {
        testService.save();
    }

}
package javaConfig;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import dao.TestDao;
import service.TestService;
import controller.TestController;

//一个配置类,相当于一个Spring配置的XML文件;
//此处没有使用包扫描,是因为所有Bean都在此类中定义了。
@Configuration
public class JavaConfig {
    @Bean
    public TestDao getTestDao() {
        return new TestDao();
    }

    @Bean
    public TestService getTestService() {
        TestService ts = new TestService();
        // 使用set方法注入testDao
        ts.setTestDao(getTestDao());
        return ts;
    }

    @Bean
    public TestController getTestController() {
        TestController tc = new TestController();
        // 使用set方法注入testService
        tc.setTestService(getTestService());
        return tc;
    }

}
package javaConfig;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import controller.TestController;

public class TestConfig {
    public static void main(String[] args) {
        // 初始化Spring容器ApplicationContext
        AnnotationConfigApplicationContext appCon = new AnnotationConfigApplicationContext(JavaConfig.class);
        TestController tc = appCon.getBean(TestController.class);
        tc.save();
        appCon.close();
    }

}

 

 

 

标签:java,--,SPRING,TestController,Bean,TestService,import,TestDao,public
来源: https://www.cnblogs.com/tszr/p/15310225.html