I am trying to configure Load Time Weaving for my Spring Boot app to properly autowire dependencies on a #Configurable java class.
Here is my configuration/main class:
package com.bignibou;
#Configuration
#EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class, ThymeleafAutoConfiguration.class, FlywayAutoConfiguration.class })
#EnableSpringConfigured
#EnableLoadTimeWeaving(aspectjWeaving = AspectJWeaving.ENABLED)
#ComponentScan
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
Here is how I start the application (my gradle build renamed the spring-instrument jar):
java -javaagent:build/lib/springinstrument.jar -jar myapp.jar
Here is the #Configurable class that does not get its dependencies autowired:
package com.bignibou.converter;
#Configurable
public class StringToDayToTimeSlotConverter implements Converter<String, DayToTimeSlot> {
#Autowired
private DayToTimeSlotRepository dayToTimeSlotRepository;//NOT AUTOWIRED!!
#Override
public DayToTimeSlot convert(String id) {
return dayToTimeSlotRepository.findOne(Long.parseLong(id));//NPE HERE!!
}
}
Here is where the class is instantiated (with new):
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = { "com.bignibou.controller" }, useDefaultFilters = false, includeFilters = { #Filter(type = FilterType.ANNOTATION, value = Controller.class),
#Filter(type = FilterType.ANNOTATION, value = ControllerAdvice.class) })
#Import(ApplicationControllerAdvice.class)
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
...
#Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new DayToTimeSlotToStringConverter());
registry.addConverter(new StringToDayToTimeSlotConverter());//INSTANTIATED HERE!
registry.addConverter(new LanguageToStringConverter());
registry.addConverter(new StringToLanguageConverter());
registry.addConverter(new AddressToStringConverter());
registry.addConverter(new StringToAddressConverter());
super.addFormatters(registry);
}
Can anyone please help figure out why StringToDayToTimeSlotConverter's dependencies are not autowired?
Very old question with at least a suggestion for a solution that I will turn into an answer so that the question can be "closed". Turn StringToDayToTimeSlotConverter into a Bean as follows:
#Bean
public class StringToDayToTimeSlotConverter implements Converter<String, DayToTimeSlot> {
#Autowired
private DayToTimeSlotRepository dayToTimeSlotRepository;
#Override
public DayToTimeSlot convert(String id) {
return dayToTimeSlotRepository.findOne(Long.parseLong(id));
}
}
Inject all available converters in WebMvcConfiguration as follows:
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = { "com.bignibou.controller" }, useDefaultFilters = false, includeFilters = { #Filter(type = FilterType.ANNOTATION, value = Controller.class),
#Filter(type = FilterType.ANNOTATION, value = ControllerAdvice.class) })
#Import(ApplicationControllerAdvice.class)
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
#Autowired
List<Converter> converters;
#Override
public void addFormatters(FormatterRegistry registry) {
for (Converter converter : converter) {
registry.addConverter(converter);
}
super.addFormatters(registry);
}
}
Related
Hi we are building custom spring security library
we need to pass {"/v1","/v2"} paths through #EnableMySpringSecurity(excludePaths = {"/v1","/v2"}) which is present in the main project to library websecurity so we can ignore those endpoints from security
#EnableMySpringSecurity(excludePaths = {"/v1","/v2"})
#EnableWebMvc
public class WebAppConfiguration extends BaseWebAppConfiguration {
Websecurity Configuration from custom JAR
#EnableWebSecurity(debug = true)
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
public static class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
public void configure(WebSecurity web){
web.ignoring().antMatchers(excludePaths );
How to pass values that are passed from #EnableMYSpringSecurity to the webSecuirty web.ignoring.antMatchers
our annotation configuration
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.TYPE)
public #interface EnableMySpringSecurity {
String[] excludePaths() default {};
}
I have tried ApplicationStartupListener but problem with this is, it is initialized after websecuirty configuration
public class ApplicationStartupListener implements
ApplicationListener<ContextRefreshedEvent> {
private ApplicationContext context;
private EnableMySSAnnotationProcessor processor;
public ApplicationStartupListener(ApplicationContext context,
EnableMySSAnnotationProcessor processor) {
this.context = context;
this.processor = processor;
}
#Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
Optional<EnableMySpringSecurity> annotation =
context.getBeansWithAnnotation(EnableMySpringSecurity.class).keySet().stream()
.map(key -> context.findAnnotationOnBean(key, EnableMySpringSecurity.class))
.findFirst();
annotation.ifPresent(enableMySpringSecurity-> processor.process(enableMySpringSecurity));
}
}
One way you can do this is with the #Import annotation:
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.TYPE)
#Import(MyWebSecurityConfiguration.class)
#EnableWebSecurity
public #interface EnableMyWebSecurity {
String[] paths() default [];
}
and then the ImportAware interface:
#Configuration
public class MyWebSecurityConfiguration implements ImportAware {
private String[] paths;
#Bean
WebSecurityCustomizer paths() {
return (web) -> web.ignoring().antMatchers(paths);
}
#Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
EnableMyWebSecurity annotation = importMetadata
.getAnnotations().get(EnableMyWebSecurity.class).synthesize();
this.paths = annotations.paths();
}
}
Note, by the way, that when you exclude paths, Spring Security cannot add security headers as part of the response. If you want those endpoints to be protected by Spring Security, but public, then consider instead:
#Configuration
public class MyWebSecurityConfiguration implements ImportAware {
private String[] paths;
#Bean
#Order(1)
SecurityFilterChain paths(HttpSecurity http) {
http
.requestMatchers((requests) -> requests.antMatchers(paths))
.authorizeRequests((authorize) -> authorize
.anyRequest().permitAll()
);
return http.build();
}
#Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
EnableMyWebSecurity annotation = importMetadata
.getAnnotations().get(EnableMyWebSecurity.class).synthesize();
this.paths = annotations.paths();
}
}
The benefit of the second approach is that Spring Security won't require authentication, but will add secure response headers.
The solution provided #jzheaux works
There is one more solution - is to use application context getBeansWithAnnoation
#EnableWebSecurity(debug = true)
#Configuration
#Order(2147483640)
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private ApplicationContext appContext;
#Override
public void configure(WebSecurity web){
Map<String,Object> beanMap = this.appContext.getBeansWithAnnotation(EnableMYSpringSecurity.class);
if(!beanMap.isEmpty()){
EnableMYSpringSecurityanno = (EnableMYSpringSecurity) this.appContext.findAnnotationOnBean(beanMap.keySet()
.iterator()
.next(),EnableMYSpringSecurity.class);
String[] permitPaths = anno.excludePaths();
Arrays.stream(permitPaths).forEach(System.out::println);
}
configuration B below is using BeanDefinitionRegistryPostProcessor to dynamically register some spring beans. However I need to access Configuration class A which is autowired inside B. A always ends up being Null which is due to the fact for BeanDefinitionRegistryPostProcessor - "All regular bean definitions will have been loaded, but no beans will have been instantiated yet"
Is there anyway i can force the configuration loading so that A is instaniated before the Configuration class B so that applicationsProperties is not always null?
A
#ConfigurationProperties(prefix = "ie.test.appname.applications")
#Configuration
#EnableAutoConfiguration
#EnableConfigurationProperties
#RefreshScope
#Data
public class ApplicationProperties {
private List<Application> applications = new ArrayList<>();
}
B
#Configuration
#Import({ ApplicationProperties.class})
#Log4j
public class ConfigurationManager {
#Autowired
private ApplicationProperties applicationProperties;
#Bean
public BeanDefinitionRegistryPostProcessor beanPostProcessor(final ConfigurableEnvironment environment) {
return new BeanDefinitionRegistryPostProcessor() {
public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0) throws BeansException {
}
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanRegistry) throws BeansException {
doSomething();
}
};
}
private void doSomething() {
List<Application> storeNamesList = applicationProperties.getApplications(); // null pointer
}
Main with component scan
#SpringBootApplication
#EnableAspectJAutoProxy
#EnableScheduling
#EnableAsync
#ComponentScan("ie.test.appname")
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication .class, args);
}
}
I used #ComponentScan on the Application class and use the #Configuration on my config class, in my config class, I want to inject beans defined in other config class by using #Autowired annotation, but when I run the application, I got null for these fields.
#Configuration
public class AConfiguration {
#Bean
public A getA(){
return ..;
}
}
#Configuration
public class BConfiguration {
#Autowired
private A a;
#Bean
public B getB() {
**something need a, but a is null**
}
}
#EnableCaching
#Configuration
public class EhcacheConfiguration extends CachingConfigurerSupport {
#Bean
#Override
public CacheManager cacheManager() {
return new EhCacheCacheManager(ehCacheCacheManager().getObject());
}
#Bean
public EhCacheManagerFactoryBean ehCacheCacheManager() {
EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean();
cmfb.setConfigLocation(new ClassPathResource("ehcache.xml"));
cmfb.setShared(true);
return cmfb;
}
}
#Configuration
#DependsOn("ehcacheConfiguration")
public class ShiroConfiguration {
#Autowired
private org.springframework.cache.CacheManager cacheManager;
}
#SpringBootApplication
#EnableTransactionManagement
public class JarApplication {
public static void main(String[] args) {
SpringApplication.run(JarApplication.class, args);
}
}
You can try this.
#Configuration
public class AConfiguration {
#Bean
public A getA(){
return ..;
}
}
#Configuration
public class BConfiguration {
#Autowired
private A a;
public B getB() {
**something need a, but a is null**
}
}
I'm using Spring Boot 1.3.2, and I notice problem, ComponentScan in my test class is not working. And I want to mock some of Spring Beans. Is spring boot blocking ComponentScan?
Test config class:
#Configuration
#ComponentScan(value = {"myapp.offer", "myapp.image"})
public class TestEdge2EdgeConfiguration {
#Bean
#Primary
public OfferRepository offerRepository() {
return mock(OfferRepository.class);
}
}
Test class:
#ContextConfiguration(classes=TestEdge2EdgeConfiguration.class, loader=AnnotationConfigContextLoader.class)
public class OfferActionsControllerTest extends AbstractTestNGSpringContextTests {
#Autowired
private OfferRepository offerRepository;
#Autowired
private OfferActionsController offerActionsController;
#BeforeMethod
public void setUp(){
MockitoAnnotations.initMocks(this);
}
#Test
public void saveOffer() {
//given
BDDMockito.given(offerRepository.save(any(Offer.class))).willReturn(new Offer());
//when
ResponseEntity<Offer> save = offerActionsController.save(new Offer());
//then
org.springframework.util.Assert.notNull(save);
}
}
Solution of this problem
Test config class, it's important to exclude SpringBootApplicationConfigutation and add #ComponentScan:
#ComponentScan(basePackages = "com.example", excludeFilters =
#ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,
value = {SpringBootApplicationConfigutation.class, MyDao.class}
)
)
#Configuration
public class TestEdge2EdgeConfiguration {
#Bean
public OfferRepository offerRepository() {
return mock(OfferRepository.class);
}
}
And test:
#SpringApplicationConfiguration(classes=TestEdge2EdgeConfiguration.class)
public class OfferActionsControllerTest extends AbstractTestNGSpringContextTests {
#Autowired
private OfferRepository offerRepository;
#Autowired
private OfferActionsController offerActionsController;
#BeforeMethod
public void resetMock() {
Mockito.reset(offerRepository);
}
#Test
public void saveOffer() {
//given
BDDMockito.given(offerRepository.save(any(Offer.class))).willReturn(new Offer());
//when
ResponseEntity<Offer> save = offerActionsController.save(new Offer());
//then
org.springframework.util.Assert.notNull(save);
}
}
I'm stuck! If I skip tests and deploy to tomcat auto wiring the configuration properties file works. In my test, it fails! I'm not sure what I'm missing.
Here is my setup:
Spring Boot v 1.2.5.RELEASE
Application.yml
git:
localRepo: './powershell-status-scripts/'
remoteRepo: 'https://github.com/...'
RepositoryProperties this class has getters and setters for the properties
#Configuration
#ConfigurationProperties(locations = "classpath:application.yml", prefix = "git", ignoreUnknownFields = false)
public class RepositoryProperties {
private String localRepo;
private String remoteRepo;
public RepositoryProperties() {
}
public String getLocalRepo() {
return localRepo;
}
public void setLocalRepo(String localRepo) {
this.localRepo = localRepo;
}
public String getRemoteRepo() {
return remoteRepo;
}
public void setRemoteRepo(String remoteRepo) {
this.remoteRepo = remoteRepo;
}
}
Application.java
#EnableAutoConfiguration
#EnableConfigurationProperties
#ComponentScan(basePackages = "com.sendash.admin")
#EnableJpaRepositories("com.sendash.admin.dao.jpa")
#EnableSwagger
public class Application extends SpringBootServletInitializer {
private static final Class<Application> applicationClass = Application.class;
private static final Logger log = LoggerFactory.getLogger(applicationClass);
public static void main(String[] args) {
SpringApplication.run(applicationClass, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(applicationClass);
}
}
GitService - Autowiring the properties works on tomcat!
#Service
#EnableConfigurationProperties
public class GitService {
#Autowired
private RepositoryProperties repositoryProperties;
public void updateLocalRepository() {
...
}
GitServiceTest this class fails on init because of a NPE. Properties is null.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = Application.class)
#Profile("test")
#TestExecutionListeners({ DependencyInjectionTestExecutionListener.class })
public class GitServiceTest {
#Autowired
private static GitService manager;
#Autowired
private static RepositoryProperties properties;
private static final String localRepoLocation = properties.getLocalRepo();
I do realize after pasting this that #EnableConfigurationProperties is on both the Application.java and the GitService.java class. Stopping the duplication does not fix the problem.
If you want to use Spring Boot in your tests, you should configure the tests accordingly. To do that, remove the ContextConfiguration and add the following:
#SpringApplicationConfiguration(classes = Application.class, initializers = ConfigFileApplicationContextInitializer.class)
This should enable injecting the configuration properties.
I did change my ContextConfiguration as suggested, but my main problem was trying to autowire a static field. It was static for #BeforeClass test setup logic so I needed to move things around a bit, but I got it working. Thanks for the suggestion.