Spring怎样基于注解显式实现自动装配

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Spring怎样基于注解显式实现自动装配

Arno_vc   2020-08-01 我要评论

本文着重讲解了Spring怎样基于注解显式实现自动装配,文中通过代码实例讲解的非常细致,对大家的工作和学习具有一定的参考学习价值,欢迎大家阅读和收藏

构建bean文件:

public class People {
  private String name = "小明";
}

编写配置类:

@Configuration
@Import(ApplicationConfig2.class)
public class ApplicationConfig {

  @Bean
  public People getPeople(){
    return new People();
  }
}

@configuration:说明这是一个配置类,功能几乎等同于<beans>标签

@Bean:说明这是一个bean,方法的返回值也就是<bean>中的class属性,方法的名称就是<bean>中的id

@Import:用于导入其它的配置类,相当于<beans>下的<import>标签

编写测试类:

public class MyTest {

  public static void main(String[] args) {
    ApplicationContext context = new AnnotationConfigApplicationContext("com.guan.config");
    People people = context.getBean("getPeople",People.class);
    System.out.println(people.getName());
  }
}

注意:这里使用AnnotationConfigApplicationContext类获得上下文

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们