配置类一@Configuration

import org.springframework.context.annotation.Configuration;

@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并
用于构建bean定义,初始化Spring容器

Spring Boot不需要在xml配置注解扫描,需要你保证你的启动Spring Boot main入口,在这些类的上层包就行。

  • @Configuation等价于<Beans></Beans>
  • @Bean等价于<Bean></Bean>
@Configuration  
public class ExampleConfiguration {  
  
    @Value("com.mysql.jdbc.Driver")  
    private String driverClassName;  
  
    @Value("jdbc://xxxx.xx.xxx/xx")  
    private String driverUrl;  
  
    @Value("root")  
    private String driverUsername;  
  
    @Value("123456")  
    private String driverPassword;  
  
    @Bean(name = "dataSource")  
    public DataSource dataSource() {  
        BasicDataSource dataSource = new BasicDataSource();  
        dataSource.setDriverClassName(driverClassName);  
        dataSource.setUrl(driverUrl);  
        dataSource.setUsername(driverUsername);  
        dataSource.setPassword(driverPassword);  
        return dataSource;  
    }  
  
    @Bean  
    public PlatformTransactionManager transactionManager() {  
        return new DataSourceTransactionManager(dataSource());  
    }  
  
}

@Autowired
private DataSource dataSource;

这个dataSource就是我们在ExampleConfiguration中配的DataSource

@Component注解也会当做配置类,但是并不会为其生成CGLIB代理Class,所以执行了两次new操作,所以是不同的对象。当时@Configuration注解时,生成当前对象的子类Class,并对方法拦截,第二次new时直接从BeanFactory之中获取对象,所以得到的是同一个对象。

原文地址:https://www.cnblogs.com/loveer/p/11312197.html