Spring Boot中如何从配置文件读取Qualifier注解值?
Got it, so you want to swap out those hardcoded "jdbc" and "prod" qualifier values with ones pulled straight from your application.properties file—super smart for keeping things flexible and easy to tweak later. Here's how to make that happen step by step:
Step 1: Add Configs to application.properties
First, define the names you want to use in your properties file. This is where you'll set the values that your code will reference:
# application.properties # Name for your JdbcTemplate bean jdbc.bean.name=jdbc # Name for your target DataSource qualifier datasource.qualifier.name=prod
Feel free to change these values anytime later—no code edits needed, just update the properties file!
Step 2: Update the JdbcTemplate Bean Definition
Modify your @Bean method to use Spring's SpEL (Expression Language) syntax (${...}) to pull the dynamic values from your properties. This works for both the bean name and the @Qualifier on the DataSource parameter:
@Bean(name = "${jdbc.bean.name}") public JdbcTemplate masterJdbcTemplate(@Qualifier("${datasource.qualifier.name}") DataSource prod) { return new JdbcTemplate(prod); }
Quick note: I removed the @Autowired from the bean method—it’s unnecessary here, Spring will automatically inject the DataSource for you as long as the qualifier matches.
Step 3: Update the Controller’s Qualifier
Do the same in your TestController to reference the dynamic bean name instead of the hardcoded string:
public class TestController{ @Autowired @Qualifier("${jdbc.bean.name}") private JdbcTemplate jtm; //..... }
How It All Comes Together
Spring resolves the ${property.key} syntax at startup, pulling the actual values from your application.properties. This keeps your bean’s name and the qualifier reference perfectly in sync without any hardcoded strings tying you down. Just double-check that your property keys match exactly between the file and the SpEL expressions—typos here will lead to "no bean found" errors!
内容的提问来源于stack exchange,提问作者Ricky

