本稿はSpringFrameworkの@Beanについて説明します。

@Beanとは

@Bean@Configurationクラスにメソッド単位で付与されます。

@Beanが付与されたクラスは原則としてDataSourceやJdbcTemplateといった"クラス"を戻り値とします。

以下、DB設定クラスのサンプルです。

@Configuration
@PropertySource({ "classpath:/jdbc.properties" })
public class DBConfig {

    @Autowired
    private Environment environment;

    @Bean
    public DataSource getDataSource() {
        final DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getProperty("jdbc.url"));
        dataSource.setUsername(environment.getProperty("jdbc.username"));
        dataSource.setPassword(environment.getProperty("jdbc.password"));
        return dataSource;
    }
}