How do I enable @Required Annotation in JavaConfig?
Hello,
I'm trying to port an existing application to JavaConfig. How do I enable the @Required annotation? In XML, I did so via the <context:annotation-config/> tag. My code is:
Code:
@ContextConfiguration(locations = "mypackage.ApplicationConfig", loader = JavaConfigContextLoader.class)
public class ReplicatedStoreTest extends AbstractTestNGSpringContextTests{
@Test
public void test() {
Assert.assertNotNull(config);
}
@Autowired
StartupParameters config;
}
It's injecting properly into the config object, but ignoring the @Required in StartupParameters
Thanks in Advance,
Steven
Harvard Children's Hospital Informatics Program
Nevermind, found the answer
Code:
@Configuration(checkRequired=true)
public class ApplicationConfig {
@Bean
public StartupConfig getConfig() {
StartupConfig startup = new StartupConfig();
return startup;
}
@Bean
public BDBWrapper getWrapper() throws DatabaseException {
return new BDBWrapper(getConfig());
}
}
Spoke too soon. Claims I need to set variables when I already have.
Thanks for the quick reply Chris,
My code is now checking the @Required annotation, but doesn't recognize it when I set it. I get "Method 'setCacheSize' is required for bean 'getConfig'" despite having clearly set the property. Did I use the annotations incorrectly? Could this have something to do with AbstractTestNGSpringContextTests?
Here's my test:
Code:
@ContextConfiguration(locations = "mydomain.ApplicationConfig", loader = JavaConfigContextLoader.class)
public class ReplicatedStoreTest extends AbstractTestNGSpringContextTests{
@Test
public void test() {
logger.debug(config);
Assert.assertNotNull(config);
}
@Autowired
StartupConfig config;
}
Here's my config:
Code:
//@PropertiesValueSource(locations="file:${user.home}/.isg/test.properties") //temporarily hidden until I can get this reading ${user.home}
@PropertiesValueSource(locations={"classpath:/myproject.properties",
"file:/home/myname/.isg/test.properties"})
@Configuration(checkRequired=true)
public abstract class ApplicationConfig {
@Bean
public StartupConfig getConfig() {
StartupConfig startup = new StartupConfig();
startup.setCacheSize(getCache());
return startup;
}
@ExternalValue(value="myproject.bdbhome")
public abstract String getBDBDir();
@ExternalValue(value="myproject.cache")
public abstract int getCache();
}
Here's the bean with the @Required annotation.
Code:
public class StartupConfig {
private long cacheSize;
public long getCacheSize() {
return cacheSize;
}
@Required
public void setCacheSize(long cacheSize) {
this.cacheSize = cacheSize;
}
}
Thanks in Advance,
Steven