Java .Spring 中不能使用自动装配,必须使用 javaconfig 来配置的前提下,能不能利用 SpEL 实现从.properties 读取属性并注入到一个 Bean 中?

2018-05-29 11:55:43 +08:00
 Newyorkcity

有 cdproperties.properties 文件,内容如下:

disc.title = "SgtPeppers's songs"
disc.artist = "The Beaties"

有一个 SgtPeppers 类,待注入 title 和 artist 属性:

public class SgtPeppers implements CompactDisc {
    private String title;
    private String artist;

    /**
     * 用 setter 方法还是构造器来注入都无所谓
     * 最好能两种方案都讲一下该如何实现     */

    public void play(){
        System.out.println("playing" + this.title + "written by" + this.artist);
    }
}

在 CDplayerConfig 中

@Configuration
public class CDPlayerConfig {

    @Bean
    public CompactDisc sgtPeppers(){
        /**
         * 最终会返回一个 SgtPeppers 类的
         * 但如何在这里进行配置,将 cdproperties.properties 中的属性值注入?
         * 不允许开启使用自动配置!
         */
    }

    @Bean
    public CDPlayer cdPlayer(CompactDisc CD){
        CDPlayer cdPlayer = new CDPlayer();
        cdPlayer.setCd(CD);
        return cdPlayer;
    }
}

谢谢。

622 次点击
所在节点    问与答
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/458603

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX