V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
Newyorkcity
V2EX  ›  问与答

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

  •  
  •   Newyorkcity · 2018-05-29 11:55:43 +08:00 · 623 次点击
    这是一个创建于 2330 天前的主题,其中的信息可能已经有所发展或是发生改变。

    有 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;
        }
    }
    

    谢谢。

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1025 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 19:17 · PVG 03:17 · LAX 12:17 · JFK 15:17
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.