@Import注解就是之前xml配置中的import标签,可以用于依赖第三方包中bean的配置和加载
在4.2之前只支持导入配置类
在4.2,@Import注解支持导入普通的java类,并将其声明成一个bean
package com.example.demo.importtest;
public class DemoService {
public void doSomething(){
System.out.println("123--ok");
}
}
package com.example.demo.importtest;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import(DemoService.class)
public class DemoConfig {
}
package com.example.demo.importtest;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class ImportMainTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext("com.example.demo.importtest");
DemoService ds = new DemoService();
ds.doSomething();
}
}
运行结果: