gpt4 book ai didi

java - Spring 按类顺序对 bean 进行排序

转载 作者:行者123 更新时间:2023-12-01 17:43:18 26 4
gpt4 key购买 nike

我有两个类,其中一个类应该在运行时在这两个类中首先执行,但情况恰恰相反。

头等舱:

@Configuration
public class A(){
@Bean
public void methodA(){}

@Bean
public void methodB(){
for(i=0;i<9;i++){
B b = new B();
b.setJdbcUrl();
b.setUsername();
b.setPassword();
}
}
}

第二类:

@Configuration
public class B() extends HikariConfig {
@Bean
public HikariDataSource mysqlDataSource(){}

@Bean(name = "someEntityManager")
public LocalContainerEntityManagerFactoryBean mysqlEntityManagerFactory(EntityManagerFactoryBuilder builder) {}

@Bean(name = "someTransactionManager")
public PlatformTransactionManager mysqlTransactionManager(@Qualifier("someEntityManager") EntityManagerFactory entityManagerFactory) {}

目前 Spring 遵循的顺序是:
1) b.mysqlDataSource()
2) b.LocalContainerEntityManagerFactoryBean mysqlEntityManagerFactory(EntityManagerFactoryBuilder构建器)
3) b.PlatformTransactionManager mysqlTransactionManager(@Qualifier("someEntityManager") EntityManagerFactoryEntityManagerFactory)
4) a.methodA()
5) a.methodB()

我的订单应该遵循Spring:
1) a.methodA()
2) a.methodB()
3) b.mysqlDataSource()
4) b.LocalContainerEntityManagerFactoryBean mysqlEntityManagerFactory(EntityManagerFactoryBuilder构建器)
5) b.PlatformTransactionManager mysqlTransactionManager(@Qualifier("someEntityManager") EntityManagerFactoryEntityManagerFactory)

并且它还必须经过代码,其中B类是唯一依赖于A类的所有url、用户名和密码设置的代码,因此必须首先启动A类。

最佳答案

您可以使用@DependsOn:

@Configuration
public class A {

@Bean
public void methodA() {
}

@DependsOn("methodA")
@Bean
public void methodB() {
for (i = 0; i < 9; i++) {
B b = new B();
b.setJdbcUrl();
b.setUsername();
b.setPassword();
}
}
}

@Configuration
@DependsOn({"methodA", "methodB"})
public class B extends HikariConfig {

@DependsOn("mysqlEntityManagerFactory")
@Bean
public HikariDataSource mysqlDataSource() {
}

@DependsOn("mysqlTransactionManager")
@Bean(name = "someEntityManager")
public LocalContainerEntityManagerFactoryBean mysqlEntityManagerFactory(EntityManagerFactoryBuilder builder) {
}

@Bean(name = "someTransactionManager")
public PlatformTransactionManager mysqlTransactionManager(@Qualifier("someEntityManager") EntityManagerFactory entityManagerFactory) {
}

}

关于java - Spring 按类顺序对 bean 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60909251/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com