一、在resources目录下建立配置文件my.properties
age=33
二、自定义PropertySourcesPlaceholderConfigurer
package cn.edu.tju.service2;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration
@PropertySource("my.properties")
public class MyConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer()
{
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
configurer.setPlaceholderPrefix("#{");
configurer.setPlaceholderSuffix("}");
return configurer;
}
}
三、在bean中使用placeholder
package cn.edu.tju.service2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class DemoService {
@Value("#{age}")
private int age;
public int getAge(){
return age;
}
}
四、配置文件,配置PropertySourcesPlaceholderConfigurer
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="cn.edu.tju.service2"/>
</beans>
五、用于测试的主类
package cn.edu.tju;
import cn.edu.tju.anno.MovieRecommender;
import cn.edu.tju.anno.MovieRecommender2;
import cn.edu.tju.service2.DemoService;
import cn.edu.tju.study.service.anno.domain.MyValueCalculator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Start20 {
public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("beans20.xml");
DemoService bean = applicationContext.getBean(DemoService.class);
System.out.println(bean.getAge());
}
}