Reputation:
I'm using Spring Framework
version 5.3.10
in an application that uses Spring JDBC for interfacing with the database.
I'm trying to isolate the SQL queries into .properties
files. I know there are many ways for doing this, but I was wondering if there is a way to inject all the values, for a given .properties
file referenced by @PropertySource("classpath:database/queries.properties")
into a Properties
(or Map
) type.
For instance, if I were to have a "repository" (or DAO, you name it) class like this:
@Repository
@RequiredArgsConstructor
@PropertySource("classpath:database/queries.properties")
public class ThisJdbc implements IThisJdbc {
private final Map<String, String> sqlStore; // ...values from queries.properties here
private final Properties sqlStore; // ...or here
@Override
public int[] batchInsert(final List<This> these) {
sqlStore.get("batch-insert");
...
}
...
}
I would like a simple way to inject what's in the .properties
file provided to that class via the aforementioned types — or any other available key/value type for that matter. The .properties
files are like usual:
find-all = select * from tb_this
find-by-col_1 = select * from tb_this where col_1 = :col_1
insert-record = insert into tb_this values (:col_1, :col_2, :col_3)
Notice that injecting
Environment
in all those classes is not an option for me ;)
I was looking for a way to use @Value
with a fixed prefix — similar to Spring Boot's @ConfigurationProperties
, but I couldn't find anything around that.
Basically, I'm trying to see if there is a way to use @PropertySource
and any Map
-like type to avoid having this:
@Bean(name = "this-queries")
public PropertiesFactoryBean thisQueries() {
final var bean = new PropertiesFactoryBean();
bean.setLocation(new ClassPathResource("database/queries.properties"));
return bean;
}
Upvotes: 0
Views: 381
Reputation: 17460
@PropertySource
is to be used in conjunction with @Configuration
classes. Having said that, try the following:
@Repository
@Configuration
@RequiredArgsConstructor
@PropertySource("classpath:database/queries.properties")
public class ThisJdbc implements IThisJdbc {
@Value("#{${queries}}")
private final Map<String, String> sqlStore; // ...values from queries.properties here
@Override
public int[] batchInsert(final List<This> these) {
sqlStore.get("batch-insert");
...
}
...
}
Assuming your queries.properties
is:
queries = {key1:'query1',key2:'query2',....}
Upvotes: 1