spring复习:(62)自定义PropertySourcesPlaceHolderConfigurer

一、在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



    



五、用于测试的主类

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


    }
}


你可能感兴趣的:(Spring,spring,java,后端)