这篇文章主要讲解了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类获得上下文

看完上述内容,是不是对Spring基于注解显式实现自动装配的方法有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。