15.

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

編集

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

@PropertySourceとは

@PropertySourceはプロパティファイルを読み込むアノテーションです。

@Configurationクラスと併用されることがよくあります。

@PropertySourceは引数にプロパティファイルのパスを指定します。

読み込まれたプロパティはEnvironmentクラスを@Autowiredすることでクラス内で使用できます。

以下、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