@Primary In Spring Framework

 @Primary In Spring Framework


@Primary
@Bean(name = "jdbcMainNamedParameterJdbcTemplate")
public NamedParameterJdbcTemplate namedParameterJdbcTemplate() {
return new NamedParameterJdbcTemplate(dataSource());
}

@Bean(name = "jdbcMainNamedParameterJdbcTemplateForReplica")
public NamedParameterJdbcTemplate namedParameterJdbcTemplateForReplica() {
return new NamedParameterJdbcTemplate(dataSourceForReplica());


In Spring Framework, @Primary is an annotation used to indicate a primary bean when multiple beans of the same type are present. When you have more than one bean of the same type, Spring needs to know which one to inject where. The @Primary annotation tells Spring that a particular bean should be given preference when there are multiple candidates.

In your code snippet, you have two beans of type NamedParameterJdbcTemplate:

  1. jdbcMainNamedParameterJdbcTemplate
  2. jdbcMainNamedParameterJdbcTemplateForReplica

Both beans are of the same type, so if you inject a NamedParameterJdbcTemplate somewhere in your application without specifying which one to use, Spring will be confused about which one to choose.

By adding @Primary to one of the beans, you're telling Spring that this bean should be preferred over others when auto-wiring by type. For example:

java@Autowired NamedParameterJdbcTemplate jdbcTemplate;

Here, if you have @Primary on jdbcMainNamedParameterJdbcTemplate, Spring will inject that bean into jdbcTemplate.

However, if you explicitly specify a bean name in @Qualifier during injection, Spring will use the bean associated with that name, regardless of whether it's marked as @Primary.

So, in summary, @Primary helps resolve ambiguity when autowiring beans by type.

Comments

Popular posts from this blog

Hibernate (Java) -- by jps sasadara

Observer Design Pattern & RxJava & @Async

JAVA uml Based cording <<< by jps sasadara >>>