唯一のdevのプロファイルにApplciationRunnerランを実行

Kshitij Bajracharya:

アプリケーションは唯一のdevのプロファイルで起動したとき、私は、ダミーデータをどのように作成するのですか?

私は、次のよ、この記事春ブーツ内のプロファイルとの仕事にします。私は、アプリケーションの起動時、唯一のdevのプロファイルにダミーデータを作成する必要があります。私はこれをどのように実現するのですか?

私のクラスの実装ApplicationRunnerと上書きrunデータを作成するための方法。私が使用することを試みた@Profile("dev")記事のように注釈をするが、データはアクティブなプロファイルの関係なく作成されます。

@SpringBootApplication
public class DemoApplication implements ApplicationRunner {

    @Autowired
    private UserService userService; //handles user saving

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Profile("dev")
    @Override
    public void run(ApplicationArguments arg0) throws Exception {
        User user = new User();
        user.setName("Dummy User");
        userService.save(user);
    }

}

application.properties、私が持っています、

spring.profiles.active=test

アクティブなプロファイルがある場合にのみ、ダミーのユーザーが作成する必要がありますdevが、それは内に作成されているtestだけでなく、プロファイル。

ケンちゃん

@Profileでマークされなければならない@Beanか、@Componentまたはそのステレオタイプ(すなわち@Serivce@Controller@Repositoryなど)

単純にそれを変更します。

@SpringBootApplication
public class DemoApplication {

    @Autowired
    private UserService userService; //handles user saving


    @Profile("dev")
    @Bean
    public ApplicationRunner devApplicationRunner(){
        return arg->{
           User user = new User();
           user.setName("Dummy User");
           userService.save(user);
        };
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

DEV ApplicationRunnerのコードはDEVプロファイルは、application.properties通じとして有効になっている場合に実行されます:

spring.profiles.active=dev

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=204767&siteId=1