I have an spring-boot application with 3 @Configuration
annotated classes: Application, DBScannerConfig and ElasticSearchConfiguration. My application also consumes configuration from a Spring Cloud Config Server.
The problem is that, when I try to annotate attributes with @Value("${key}")
inside the DBScannerConfig class, the properties don't get injected. However, if I use the @Value("${key}")
annotation in the other two classes, the configuration works well.
I actually think it could be related to the @MapperScan
annotation present in my DBScannerConfig configuration class.
What I would like to do is to either be able to retrieve properties or autowire spring's datasource in my @MapperScan
annotated class, but I'm not being able to achieve such thing.
Does anyone faced this problem before? Here's the code:
Application.java
@SpringBootApplication
@EnableElasticsearchRepositories("org.myapp.elastic.repository")
@ComponentScan(basePackages = {"org.myapp"})
public class Application extends WebSecurityConfigurerAdapter {
private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);
// @Autowired
// DataSource dataSource;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
//Other Stuff for Spring Security
}
DBScannerConfig.java
@Configuration
@MapperScan("org.myapp.persistence.mapper")
public class DBScannerConfig{
@Autowired
DataSource dataSource;
@Bean(name = "mySqlSessionFactory")
public SqlSessionFactory mySqlSessionFactory() {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setTypeAliasesPackage("org.myapp.persistence.entity");
SqlSessionFactory sqlSessionFactory = null;
try {
sqlSessionFactory = sessionFactory.getObject();
} catch (Exception e) {
LOGGER.error("Error creating mySqlSessionFactory", e);
}
return sqlSessionFactory;
}
}
If I uncomment the @Autowired
datasource in Application.java I get a valid object. However, in the DBScannerConfig.java what I get is NULL.
I tried to autowire the Datasource object inside my Application.java class and then use it in the DBSCannerConfig.java with no luck. As soon as I add the @MapperScan
annotation into the Application.java class it stops autowiring the spring datasource.