spring复习:(62)自定义PropertySourcesPlaceHolderConfigurer
  Ta2cNb9VdLMk 2023年11月02日 31 0


一、在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());


    }
}


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  2Vtxr3XfwhHq   2024年05月17日   55   0   0 Java
  Tnh5bgG19sRf   2024年05月20日   110   0   0 Java
  8s1LUHPryisj   2024年05月17日   46   0   0 Java
  aRSRdgycpgWt   2024年05月17日   47   0   0 Java
Ta2cNb9VdLMk