二、Java Config

1、使用Java配置类装配Bean

对象之间的依赖关系,通过配置方法中的参数实现注入
两个注解:
(1)@Configuration
该注解标明这是个配置类,该类配置说明了如何在Spring应用的上下文中进行创建和装配Bean
(2)@Bean
该注解告诉Spring将这个方法返回的对象注册为Bean

2、创建dao、service、controller

  • applicationContext文件代码:
    <bean id="TestController" class="com.neuedu.controller.TestController" autowire="byType">
        <!--<property name="testService" ref="TestService"></property>  -->
    </bean>
    
    <bean id="TestService" class="com.neuedu.service.TestService">
        <property name="testDao" ref="TestDao"></property>
    </bean>
    
    <bean id="TestDao" class="com.neuedu.dao.TestDao"></bean>
  • TestController 代码:
public  class TestController {
    private TestService testService;

    public void setTestService(TestService testService) {
        this.testService = testService;
    }
    public void test() {
        testService.test();
    }
}
  • TestService 代码:
public class TestService {
    private TestDao testDao;

    public void setTestDao(TestDao testDao) {
        this.testDao = testDao;
    }
    public void test() {
        System.out.println(testDao);
    }
}
  • TestDao不写任何代码

3、创建一个配置类AppConfig

代码如下:

@Configuration
public class AppConfig{
  @Bean
  public TestDao getTestDao(){
    return new TestDao();
  }
  @Bean
  public TestService getTestService (TestDao testDao){
    TestService testService=new TestService ();
    testService.setTestDao(testDao);
    return testService;
  }
  @Bean
  public TestController getTestController  (TestService testService){
    TestController testController =new TestController ();
    testController .setTestService (testService);
    return testController ;
  }
}
  • 测试代码
    @Test
    public void test() {
        ApplicationContext context = new AnnotationConfigApplicationContext(Appconfig.class);
        TestController testController = context.getBean(TestController.class);
        testController.test();
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容