zoukankan      html  css  js  c++  java
  • 吴裕雄天生自然SPRINGSpring 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();
        }
    
    }

     

  • 相关阅读:
    BZOJ 3629 JLOI2014 聪明的燕姿 约数和+DFS
    [BZOJ3594] [Scoi2014]方伯伯的玉米田 二维树状数组优化dp
    BZOJ 3319 黑白树 并查集+线段树
    BZOJ 2500 幸福的道路(race) 树上直径+平衡树
    BZOJ1875: [SDOI2009]HH去散步 图上边矩乘
    【BZOJ3887】【Usaco2015 Jan】Grass Cownoisseur Tarjan+Spfa
    NOIP2010 引水入城 贪心+DFS
    【BZOJ3038】上帝造题的七分钟2 线段树
    COGS 930. [河南省队2012] 找第k小的数 主席树
    BZOJ2631 tree(伍一鸣) LCT 秘制标记
  • 原文地址:https://www.cnblogs.com/tszr/p/15310225.html
Copyright © 2011-2022 走看看