项目中使用Quartz,需要配置db信息,但是因为yml里面已经配置了,不能在 quartz.properties 里面重复配置,所以直接从datasource里面获取,又因为proj中datasouce的实现类不一定,所以不能直接强转实现类.
package <%=packageName%>.config;
import <%=packageName%>.schedule.factory.TaskJobFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import java.io.IOException;
import javax.sql.DataSource;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.Properties;
@Configuration
public class QuartzConfiguration {
@Autowired
TaskJobFactory jobFactory;
@Autowired
private DataSource dataSource;
@Bean(name = "SchedulerFactory")
@Qualifier("QuartzSchedulerFactory")
public SchedulerFactoryBean schedulerFactoryBean() throws IOException, SQLException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
propertiesFactoryBean.setProperties(getDatasourceProperties());
propertiesFactoryBean.afterPropertiesSet();
SchedulerFactoryBean factory = new SchedulerFactoryBean();
factory.setQuartzProperties(propertiesFactoryBean.getObject());
factory.setJobFactory(jobFactory);
return factory;
}
private Properties getDatasourceProperties() throws IOException, SQLException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Properties properties = new Properties();
Class c = dataSource.getClass();
Method getPassword = c.getMethod("getPassword", null);
Method getUsername = c.getMethod("getUsername", null);
Method getDriver = c.getMethod("getDriverClassName", null);
Object driver = getDriver.invoke(dataSource, null);
Object pwd = getPassword.invoke(dataSource, null);
Object username = getUsername.invoke(dataSource, null);
properties.setProperty("org.quartz.dataSource.myDS.driver", driver.toString());
properties.setProperty("org.quartz.dataSource.myDS.URL", dataSource.getConnection().getMetaData().getURL());
properties.setProperty("org.quartz.dataSource.myDS.user", username.toString());
properties.setProperty("org.quartz.dataSource.myDS.password", pwd.toString());
return properties;
}
}