我尝试学习SpEl,并从属性设置对象字段值。但是结果对象字段变为空。这是我的代码
配置类:
@Configuration
@ComponentScan(basePackageClasses = ExpressiveConfig.class)
@PropertySource("classpath:
/fourthversion/chapter3.placeholders/app.properties")
public class ExpressiveConfig {
@Bean
public
static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
Class,我尝试在其中设置字段值:
@Component
public class BlankDisc implements CompactDisc {
private String title;
private String artist;
public BlankDisc(@Value("#{systemProperties['disc.title']}") String title,
@Value("#{systemProperties['disc.artist']}") String artist)
{
this.title = title;
this.artist = artist;
}
getters and setters
}
这是我的考试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ExpressiveConfig.class)
public class BlankDiskTest {
@Autowired
private BlankDisc blankDisc;
@Test
public void isBlankDiscNotNull() {
assertNotNull(blankDisc);
System.out.println(blankDisc.getTitle());
System.out.println(blankDisc.getArtist());
}
}
通过测试,对象不为null,但系统打印null,null 为什么未设置字段值?
PS
如果我这样做却是这样:
public BlankDisc(@Value("${disc.title}") String title,
@Value("${disc.artist}") String artist) {
this.title = title;
this.artist = artist;
}
然后一切正常。
答案 0 :(得分:0)
public BlankDisc(@Value("#{systemProperties['disc.title']}") String title,
@Value("#{systemProperties['disc.artist']}") String artist)
{
this.title = title;
this.artist = artist;
}
由于您是从系统属性中初始化数据的,因此需要确保数据存在
@Test
public void isBlankDiscNotNull() {
assertNotNull(blankDisc);
assertNotNull(System.getProperty("disc.title"));
assertNotNull(System.getProperty("disc.artist"));
assertEquals(blankDisc.getTitle(),System.getProperty("disc.title"));
assertEquals(blankDisc.getArtist(),System.getProperty("disc.artist"));
System.out.println(blankDisc.getTitle());
System.out.println(blankDisc.getArtist());
}