@Import注解

来源:互联网 发布:115网络异常请重试 编辑:程序博客网 时间:2024/06/10 01:13
@Import注解就是之前xml配置中的import标签,可以用于依赖第三方包中bean的配置和加载
在4.2之前只支持导入配置类
在4.2,@Import注解支持导入普通的java类,并将其声明成一个bean

public class DemoService {    public void doSomething(){        System.out.println("ok");    }}


import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Import;@Configuration@Import(DemoService.class)//在spring 4.2之前是不不支持的public class DemoConfig {}


运行

import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main {    public static void main(String[] args) {        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com..example");        DemoService ds = context.getBean(DemoService.class);        ds.doSomething();    }}


输出结果
ok