Spring重写配置

0

SpringBoot自动配置很好用,但是有时候会出现一些情况就是自动配置里面有些配置并不能通过配置文件修改,这时候就可以使用@Bean@Configuration或者@Configuration@PostConstruct轻松实现。

例如activiti的字体配置和IdGenerator配置可以使用下面方法:

import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.impl.cfg.IdGenerator;
import org.activiti.spring.SpringProcessEngineConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Config {

//	@Autowired
//	private ProcessEngineConfiguration processEngineConfiguration;
//	
//	@PostConstruct
//	public void init() {
//		this.reset(this.processEngineConfiguration);
//	}
	
	@Bean
	public ProcessEngineConfiguration processEngineConfiguration(ProcessEngineConfiguration processEngineConfiguration) {
		this.reset(processEngineConfiguration);
		return processEngineConfiguration;
	}
	
	private void reset(ProcessEngineConfiguration processEngineConfiguration) {
		// 修改字体解决中文乱码
		processEngineConfiguration.setLabelFontName("宋体");
		processEngineConfiguration.setActivityFontName("宋体");
		processEngineConfiguration.setAnnotationFontName("宋体");
		// 修改ID暂时没有发现最有解决方案
		// 以下代码不建议使用没有经过测试
		if(processEngineConfiguration instanceof SpringProcessEngineConfiguration) {
			final IdGenerator idGenerator = new IdGenerator() {
				@Override
				public String getNextId() {
					// TODO:自行实现
					return System.nanoTime() + "";
				}
			};
			final SpringProcessEngineConfiguration springProcessEngineConfiguration = (SpringProcessEngineConfiguration) processEngineConfiguration;
			springProcessEngineConfiguration.setIdGenerator(idGenerator);
			springProcessEngineConfiguration.getBpmnDeployer().setIdGenerator(idGenerator);
			springProcessEngineConfiguration.getDbSqlSessionFactory().setIdGenerator(idGenerator);
		}
	}

}

当然还可以使用使用Spring Bean生命周期其他接口实现:https://www.acgist.com/article/1105.html