一、理解
@Import注解就是之前xml配置中的import标签,可以用于依赖第三方包中bean的配置和加载
在4.2之前支持导入配置类
在4.2@Import注解支持导入普通的java类,并将其声明成一个bean
二、代码实现
package com.springboot.demo.importAnnotation;
public interface Person {
public void showPosition();
}
package com.springboot.demo.importAnnotation;
public class Teacher implements Person {
@Override
public void showPosition() {
System.out.println("i am a teacher");
}
}
package com.springboot.demo.importAnnotation;
public class Student implements Person {
@Override
public void showPosition() {
System.out.println("i am a student");
}
}
导入普通的java类
package com.springboot.demo.importAnnotation;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import({Teacher.class,Student.class})
public class MainConfiguration {
}
package com.springboot.demo.importAnnotation;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class ImportAnnotationTest {
public static void main (String args[]){
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfiguration.class);
Teacher t = context.getBean(Teacher.class);
t.showPosition();
Student s = context.getBean(Student.class);
s.showPosition();
}
}
运行结果:
i am a teacher
i am a student