Last active
September 17, 2021 12:19
-
-
Save ringoluo/1d10cd42496e53fd7a8c to your computer and use it in GitHub Desktop.
Dynamic constructor arguments when wiring spring beans
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Configuration | |
@ComponentScan | |
@EnableAutoConfiguration | |
public class Application implements CommandLineRunner { | |
public static void main(String[] args) { | |
SpringApplication.run(Application.class, args); | |
} | |
@Bean(name = "state") | |
@Scope("prototype") | |
State state(String stateName) { | |
return new State(stateName); | |
} | |
@Bean(name = "country") | |
@Scope("prototype") | |
Country country(String countryName) { | |
return new Country(countryName); | |
} | |
@Autowired | |
private ApplicationContext context; | |
@Override | |
public void run(String... args) throws Exception { | |
Country usa = (Country) context.getBean("country", "USA"); | |
usa.report(); | |
} | |
} | |
class Country { | |
private State state; | |
@Autowired | |
private ApplicationContext context; | |
private String countryName; | |
public Country(String countryName) { | |
this.countryName = countryName; | |
} | |
@PostConstruct | |
public void init() { | |
String stateName = WorldMap.lookupState(this.countryName); | |
this.state = (State) context.getBean("state", stateName); | |
} | |
public void report() { | |
System.out.println(state); | |
} | |
} | |
class State { | |
private String stateName; | |
public State(String stateName) { | |
this.stateName = stateName; | |
} | |
@Override | |
public String toString() { | |
return "State [stateName=" + stateName + "]"; | |
} | |
} | |
class WorldMap { | |
public static String lookupState(String country) { | |
if (country.equalsIgnoreCase("USA")) { | |
return "New York"; | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment