定义接口
public interface HelloWorld {
void printMsg(String msg);
}
接口实现类
public class HelloWorldImpl implements HelloWorld {
@Override
public void printMsg(String msg) {
System.out.println("Hello : " + msg);
}
}
使用 @Configuration 注释告诉 Spring,这是核心的 Spring 配置文件,并通过 @Bean 定义 bean。
@Configuration
public class AppConfig {
@Bean(name="helloBean")
public HelloWorld helloWorld() {
return new HelloWorldImpl();
}
}
这里等效于在xml配置文件中配置
<bean id="helloBean" class="com.yuan.hello.impl.HelloWorldImpl">
测试结果
public class App {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
HelloWorld hw = (HelloWorld) context.getBean("helloBean");
hw.printMsg("Spring Java Config");
}
}
如想加载多个配置文件可以使用@Import注解,例如在已有Teacher.java,Student.java两个Bean情况下
public class Teacher {
public void printMsg(String msg) {
System.out.println("Teacher : " + msg);
}
}
public class Student {
public void printMsg(String msg) {
System.out.println("Student : " + msg);
}
}
再将两个Bean用@Configuration声明
@Configuration
public class TeacherConfig {
@Bean(name="teacher")
public Teacher teacher(){
return new Teacher();
}
}
@Configuration
public class StudentConfig {
@Bean(name="student")
public Student student(){
return new Student();
}
}
使用@Import加载多个配置文件
@Configuration
@Import({ TeacherConfig.class, StudentConfig.class })
public class AppConfig {
}
测试:
public class App {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(
AppConfig.class);
Teacher teacher = (Teacher) context.getBean("teacher");
teacher.printMsg("Hello 1");
Student student = (Student) context.getBean("student");
student.printMsg("Hello 2");
}
}