3.

【Spring】@Beanアノテーションとは

編集

本稿は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;
    }
}

 

 

編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. @After
  2. @Autowired
  3. @Bean
  4. @Before
  5. @Column
  6. @Component
  7. @Configuration
  8. @Controller
  9. @Data
  10. @Entity
  11. @GeneratedValue
  12. @Id
  13. @Modifying
  14. @PathVariable
  15. @PropertySource
  16. @Repository
  17. @RequestBody
  18. @RequestMapping
  19. @ResponseBody
  20. @RestController
  21. @Service
  22. @SpringBootApplication
  23. @Table
  24. @Transactional
  25. @Value