spring中@PropertySource注解的使用

概述:

The @PropertySource annotation provides a convenient and declarative mechanism for adding a
PropertySource to Spring’s Environment.

案例:

一个properties文件的代码如下:

jdbc.properties的代码如下:

jdbc.driverClassName=org.hsqldb.jdbcDriver
配置类的代码如下(里面有main方法,这次直接在这个配置类里测试了):
package com.timo.propertySource;

import com.timo.profile.domain.Alarm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

@Configuration
@PropertySource("classpath:jdbc.properties")
public class AppConfig {
    //这个Environment是自动注入的:
    @Autowired
    Environment env;
    @Bean
    public Alarm alarm(){
        Alarm alarm = new Alarm();
        alarm.setName(env.getProperty("jdbc.driverClassName"));
        return alarm;
    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.register(AppConfig.class);
        applicationContext.refresh();
        String name = applicationContext.getBean(Alarm.class).getName();
        System.out.println("name="+name);
    }
}

 



posted @ 2017-12-01 15:09  技术让世界更精彩  阅读(4994)  评论(0编辑  收藏  举报