Spring JavaConfig

定义接口

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");

    }
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值