我对SO很陌生,我正在根据环境(开发,生产,测试)加载环境配置和属性的任务,我已经成功地实现了DAO级别的数据库配置通过使用<beans profile="profile.name">
。在前端,我必须根据环境获取属性文件,所以我有不同的文件。为了调用它,我尝试了以下代码:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class PropertiesUtility {
@Value("${mount.images.webpath}")
private String imagePath;
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
@Override
public String toString() {
return "PropertiesUtility{" +
"imagePath='" + imagePath + ''' +
'}';
}
}
我的上下文.xml配置:
<context:annotation-config/>
<beans profile="dev">
<context:property-placeholder location="classpath:properties/pharmisa_web_conf.properties"
ignore-unresolvable="true" />
</beans>
<beans profile="test">
<context:property-placeholder location="classpath:properties/pharmisa_web_test_conf.properties"
ignore-unresolvable="true" />
</beans>
调用属性实用程序:
public class URLUtility {
@SpringBean //even @Autowired also not working
static PropertiesUtility propertiesUtility;
public static String getCompanyLogoUrl(int id) {
StringBuffer sb = new StringBuffer(getImagePath());
boolean isEndWithSlash=PharmisaStringUtils.endsWith(getImagePath(),"/");
if (!isEndWithSlash){
sb.append("/");
}
sb.append(id);
sb.append("/");
return sb.toString();
}
private static final String getImagePath() {
return propertiesUtility.getImagePath().trim();
}
}
春季JunitTest
测试工作完美
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/pharmisa_web-context.xml"})
@ActiveProfiles(profiles = "test")
public class CompanyServiceImplTest {
@Autowired
PropertiesUtility propertiUtility;
@Test
public void testAppProperties() {
System.out.println(propertiUtility.getImagePath());
}
}
当我尝试在检票口页面中注入属性实用程序类时。我没有获得属性的值。因为它没有注射。我知道检票口有@SpringBean
,但即使它不起作用。
无论如何,是否有任何替代欢迎的价值。
为了您的进一步,我已经点击了链接
http://examples.javacodegeeks.com/enterprise-java/spring/load-environment-configurations-and-properties-with-spring-example/
@Component
或@Autowire
工作,URLUtility
应该是一个Spring bean。
@SrpingBean
仅在 Wicket 组件中自动工作。在其他任何事情中,您都需要明确地"要求注射"Injector.get().inject(this)
.