dharam
dharam

Reputation: 8106

Difference between scanning @Configuration classes and @Import configuration classes

I have been using Spring 3.2+ for some time now, Most of the time I am able to use either of the below options and it works, but I want to know if there is any specific difference.

Here is my JndiConfig java configuration class:

@Configuration
public class JndiConfig {

@Bean(name = "dataSource")
public DataSource dataSource() throws Exception {
    BasicDataSource datasource = new BasicDataSource();
    datasource.setDriverClassName("com.mysql.jdbc.Driver");
    datasource.setUrl("jdbc:mysql://localhost:3306/csdb");
    datasource.setUsername("root");
    datasource.setPassword("root");
    datasource.setValidationQuery("SELECT 1");
    return datasource;
}
}

I can use the following options:

OPTION 1

@Configuration
@Import({JndiConfig.class})
@EnableWebSecurity
public class SecurityConfig  extends WebSecurityConfigurerAdapter  {

@Autowired
private DataSource dataSource;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

    auth.jdbcAuthentication().dataSource(dataSource);

}

}

OPTION 2

@Configuration
@EnableWebSecurity
@ComponentScan(basePackages = "com.security"
public class SecurityConfig  extends WebSecurityConfigurerAdapter  {

@Autowired
private DataSource dataSource;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

    auth.jdbcAuthentication().dataSource(dataSource);

}

}

In the option 1 I import the JndiConfig where as in option 2 I just do a component scan for JndiConfig.

Can anyone explain me the difference between these two?

Thanks.

Upvotes: 1

Views: 898

Answers (1)

Gabriel Ruiu
Gabriel Ruiu

Reputation: 2803

Right now I can only figure out two differences:

  • the obvious one that, by using component scan, you can also pickup other components, not just the configuration class, that might be in the same package. This can lead to importing beans that you might not want, but I find that unlikely
  • when using @Import, you have the option of implementing the ImportAware interface on the class that gets imported, and this gives you access to the annotation metadata of the importing class, if it is useful to you

Upvotes: 1

Related Questions