• SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-007-给BEAN运行时注入值placeholder、@Value


    一、用placeholder给bean运行时注入值的步骤

    Spring取得placeholder的值是用${...}

    1.声明placeholder bean

    (1)java方式

    In order to use placeholder values, you must configure either a PropertyPlaceholder-
    Configurer bean or a PropertySourcesPlaceholderConfigurer bean. Starting with
    Spring 3.1, PropertySourcesPlaceholderConfigurer is preferred because it resolves
    placeholders against the Spring Environment and its set of property sources.
    The following @Bean method configures PropertySourcesPlaceholderConfigurer
    in Java configuration:

    @Bean
    public
    static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
    }

    (2)xml方式

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans xmlns="http://www.springframework.org/schema/beans"
     3   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     4   xmlns:c="http://www.springframework.org/schema/c"
     5   xmlns:context="http://www.springframework.org/schema/context"
     6   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
     7         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
     8 
     9   <context:property-placeholder
    10     location="com/soundsystem/app.properties" />
    11 
    12   <bean class="com.soundsystem.BlankDisc"
    13     c:_0 = "${disc.title}"
    14     c:_1 = "${disc.artist}"/>
    15 
    16 </beans>

    2.注入

    1.在java文件中用 @Value

    如构造函数

    public BlankDisc(
    @Value("${disc.title}") String title,
    @Value("${disc.artist}") String artist) {
        this.title = title;
        this.artist = artist;
    }

    2.xml

    <bean id="sgtPeppers"
    class="soundsystem.BlankDisc"
    c:_title="${disc.title}"
    c:_artist="${disc.artist}" />
  • 相关阅读:
    前端展示(四)
    小谢第66问:页面关闭鼠标光标
    小谢第64问:nuxt项目中增加百度分析统计
    js 判断当前是手机还是电脑
    布谷鸟自定义教程
    vs code常用插件及配置
    小程序几件小事儿
    删除 json 数据中的某一项
    小程序图片预览
    小程序 navigator 取消点击效果
  • 原文地址:https://www.cnblogs.com/shamgod/p/5237569.html
Copyright © 2020-2023  润新知