Spring换豆镜

iszxjhcz  于 2023-11-16  发布在  Spring
关注(0)|答案(1)|浏览(103)

我有下面的bean,它从数据库中获取值

@Bean
fun getCronValue(): String {
   val cron = settingRepository.findByKey("batch_cron_expression")
   return cron?.value ?: applicationProperties.batch.cronExpression
}

字符串
然后我用这个bean到@Scheduled

@Scheduled(cron = "#{@getCronValue}")


我希望当值从数据库中更改时,bean自动读取新值,而无需重新启动应用程序

mum43rcc

mum43rcc1#

您可以尝试使用Spring RepositoryEventServer。
示例代码
application.properties:

spring.main.allow-bean-definition-overriding=true

字符串
AppConfig:

@Bean
    public LatestCustomerId customerIdLatest() {
        LatestCustomerId id = new LatestCustomerId();
        id.setId(-1);
        return id;
    }


CustomerEventName:

@RepositoryEventHandler(CustomerDo.class)
@RequiredArgsConstructor
public class CustomerEventHandler {

    private final ApplicationContext applicationContext;

    @HandleAfterSave
    public void handleAuthorAfterSave(CustomerDo customerDo) {
        AutowireCapableBeanFactory factory = applicationContext.getAutowireCapableBeanFactory();
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) factory;
        registry.removeBeanDefinition("customerIdLatest");

        GenericBeanDefinition myBeanDefinition = new GenericBeanDefinition();
        myBeanDefinition.setBeanClass(LatestCustomerId.class);
        myBeanDefinition.setScope(BeanDefinition.SCOPE_SINGLETON);

        MutablePropertyValues mpv = new MutablePropertyValues();
        mpv.add("id", Integer.valueOf(customerDo.getId()));
        myBeanDefinition.setPropertyValues(mpv);

        registry.registerBeanDefinition("customerIdLatest", myBeanDefinition);
    }
}


客户控制器:

@RestController
@RequestMapping("api/customer")
@RequiredArgsConstructor
public class CustomerController {

    private final CustomerRepository customerRepository;
    private final CustomerMapper customerMapper;
    private final CustomerEventHandler customerEventHandler;

    @Autowired
    private LatestCustomerId latestCustomerId;

    @PostMapping("/")
    public ResponseEntity<CustomerDto> createCustomer(CustomerDto customerDto) {

        CustomerDo customerDo = customerRepository.save(customerMapper.toCustomerDo(customerDto));
        customerDto = customerMapper.toCustomerDto(customerDo);

        customerEventHandler.handleAuthorAfterSave(customerDo);
        
        return new ResponseEntity<>(customerDto, HttpStatus.CREATED);
    }

相关问题