Spring MVC Java Config (конфигурация с аннотациями) для application-context.xml
Пример преобразования application-context.xml в конфигурацию Spring MVC Java Config (конфигурация с аннотациями).
Обзор приложения Spring MVC + AngularJS + Bootstrap + HTML5
Используемые технологии и библиотеки
- Spring MVC 4.2.4.Release
1. Описание задачи
Преобразовать настройки application-context.xml в аналогичный по функционалу Java класс с использованием аннотаций.
2. Структура проекта
Это продолжение первой и второй и третьей статей по преобразованию xml конфигурации приложения на Java конфигурацию.
3. application-context.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 |
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:context="http://www.springframework.org/schema/context" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd"> <!--find property file. See bean id='dataSource' for example ${jdbc.hsqldb.driverClass}--> <context:property-placeholder location="classpath:util.properties" /> <!-- XML Bean Definitions --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.hsqldb.driverClass}" /> <property name="url" value="${jdbc.hsqldb.url}" /> <property name="username" value="${jdbc.hsqldb.username}" /> <property name="password" value="${jdbc.hsqldb.password}" /> </bean> <!-- initialize Embedded DataSource. Встроенная база данных--> <jdbc:initialize-database data-source="dataSource"> <jdbc:script location="classpath:dbschema.sql"/> <jdbc:script location="classpath:test-data.sql"/> </jdbc:initialize-database> <!-- Java Mail Configuration --> <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="username" value="${java.mail.username}"/> <property name="password" value="${java.mail.password}"/> <property name="port" value="465"/> <property name="javaMailProperties"> <props> <prop key="mail.smtp.auth">true</prop> <prop key="mail.smtp.starttls.enable">true</prop> <prop key="mail.smtp.starttls.required">true</prop> <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop> <prop key="mail.smtp.host">${java.mail.host}</prop> </props> </property> </bean> <!-- Velocity Email Template Config Bean --> <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean"> <property name="resourceLoaderPath" value="/WEB-INF/email-templates/"/> </bean> <!-- REST template configuration --> <bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/> <!--Do not forget activate @Transactional JPA annotation with <annotation-driven/>--> <!-- JPA Persistence Context and EntityManager configuration --> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" > <!--packagesToScan - search Entity and mapping them --> <property name="packagesToScan"> <list> <value>ru.javastudy.mvcHtml5Angular.mvc.bean</value> <value>ru.javastudy.mvcHtml5Angular.mvc.rest.model</value> </list> </property> <property name="dataSource" ref="dataSource" /> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" > <property name="generateDdl" value="true" /> <property name="showSql" value="true" /> </bean> </property> <property name="jpaProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">false</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> </bean> <!-- Automatic Transaction Participation--> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <!--not uses but could autowired in JDBCExample bean--> <!-- <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> --> <!-- Quartz scheduling configuration --> <task:annotation-driven/> <!-- Quartz simple trigger --> <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean"> <property name="jobDetail" ref="simpleQuartzJob" /> <property name="repeatInterval" value="1000" /> <property name="startDelay" value="1000" /> </bean> <!-- Quartz cron trigger --> <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> <property name="jobDetail" ref="quartzCronJob"/> <property name="cronExpression" value="0/30 * * * * ?" /> <!-- every 30 seconds (seconds, minutes, hours, day of month, month, day of week, year(optional)) --> </bean> <!-- Quartz job --> <bean id="simpleQuartzJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="simpleQuartzTask" /> <property name="targetMethod" value="simpleTaskMethod" /> </bean> <!-- Quartz cron job --> <bean id="quartzCronJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="cronQuartzTask" /> <property name="targetMethod" value="cronTaskMethod" /> </bean> <!-- Quartz simple task --> <bean id="simpleQuartzTask" class="ru.javastudy.mvcHtml5Angular.mvc.quartz.QuartzTask" /> <!-- Quartz cron task --> <bean id="cronQuartzTask" class="ru.javastudy.mvcHtml5Angular.mvc.quartz.CronQuartzTask" /> <!-- Quartz Scheduler --> <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="jobDetails"> <list> <ref bean="simpleQuartzJob" /> <ref bean="quartzCronJob" /> </list> </property> <property name="triggers"> <list> <ref bean="simpleTrigger" /> <ref bean="cronTrigger" /> </list> </property> </bean> <!-- ScheduleTask example. Use <context:component-scan base-package="ru.javastudy.mvcHtml5Angular.mvc.scheduling"/> and @Component on ru.javastudy.mvcHtml5Angular.mvc.scheduling.ScheduleTask or <bean id="scheduleTask" class="ru.javastudy.mvcHtml5Angular.mvc.scheduling.ScheduleTask"/> --> <!--End scheduling configuration --> </beans> |
4. ApplicationConfig
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 |
package ru.javastudy.mvcHtml5Angular.javaconfig; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.io.Resource; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.init.DataSourceInitializer; import org.springframework.jdbc.datasource.init.DatabasePopulator; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.quartz.*; import org.springframework.ui.velocity.VelocityEngineFactoryBean; import org.springframework.web.client.RestTemplate; import ru.javastudy.mvcHtml5Angular.mvc.quartz.CronQuartzTask; import ru.javastudy.mvcHtml5Angular.mvc.quartz.QuartzTask; import java.util.Properties; /** * Created for JavaStudy.ru on 28.05.2016. * application-context.xml analogue */ @Configuration @PropertySource(value = "classpath:util.properties") //<context:property-placeholder location=".." /> @ComponentScan(basePackages = "ru.javastudy.mvcHtml5Angular.mvc.scheduling") @EnableScheduling //task:annotation-driven public class ApplicationConfig { /** * @PropertySource annotation does not automatically * register a PropertySourcesPlaceholderConfigurer with Spring. * So we need to initialize this bean. */ @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } @Value("${jdbc.hsqldb.driverClass}") private String driverClass; @Value("${jdbc.hsqldb.url}") private String jdbcUrl; @Value("${jdbc.hsqldb.username}") private String jdbcUserName; @Value("${jdbc.hsqldb.password}") private String jdbcPassword; @Value("classpath:dbschema.sql") private Resource dbschemaSqlScript; @Value("classpath:test-data.sql") private Resource testDataSqlScript; /** * <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> */ @Bean(name = "dataSource") public DriverManagerDataSource getDriverManagerDataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(driverClass); dataSource.setUrl(jdbcUrl); dataSource.setUsername(jdbcUserName); dataSource.setPassword(jdbcPassword); return dataSource; } /** * <jdbc:initialize-database data-source="dataSource"> * initialize Embedded DataSource. Встроенная база данных */ @Bean public DataSourceInitializer dataSourceInitializer() { final DataSourceInitializer initializer = new DataSourceInitializer(); initializer.setDataSource(getDriverManagerDataSource()); initializer.setDatabasePopulator(getDatabasePopulator()); return initializer; } private DatabasePopulator getDatabasePopulator() { final ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); populator.addScript(dbschemaSqlScript); populator.addScript(testDataSqlScript); return populator; } /** * Java Mail Configuration */ @Value("${java.mail.username}") String mailUsername; @Value("${java.mail.password}") String mailPassword; @Value("${java.mail.host}") String mailHost; /** * <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> */ @Bean(name = "mailSender") public JavaMailSenderImpl getJavaMailSender() { JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl(); javaMailSender.setUsername(mailUsername); javaMailSender.setPassword(mailPassword); javaMailSender.setPort(465); Properties javaMailProperties = new Properties(); javaMailProperties.put("mail.smtp.auth", true); javaMailProperties.put("mail.smtp.starttls.enable", true); javaMailProperties.put("mail.smtp.starttls.required", true); javaMailProperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); javaMailProperties.put("mail.smtp.host", mailHost); javaMailSender.setJavaMailProperties(javaMailProperties); return javaMailSender; } /** * <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean"> */ @Bean(name = "velocityEngine") public VelocityEngineFactoryBean getVelocityEngineFactoryBean() { VelocityEngineFactoryBean bean = new VelocityEngineFactoryBean(); bean.setResourceLoaderPath("/WEB-INF/email-templates/"); return bean; } /** * <bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/> */ @Bean(name = "restTemplate") public RestTemplate getRestTemplate() { return new RestTemplate(); } /** * <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" > */ @Bean(name = "entityManagerFactory") public LocalContainerEntityManagerFactoryBean getLocalContainerEntityManagerFactoryBean() { LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setPackagesToScan(new String[] {"ru.javastudy.mvcHtml5Angular.mvc.bean","ru.javastudy.mvcHtml5Angular.mvc.rest.model"}); em.setDataSource(getDriverManagerDataSource()); JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); ((HibernateJpaVendorAdapter)vendorAdapter).setGenerateDdl(true); ((HibernateJpaVendorAdapter)vendorAdapter).setShowSql(true); em.setJpaVendorAdapter(vendorAdapter); Properties jpaProperties = new Properties(); jpaProperties.put("hibernate.dialect","org.hibernate.dialect.HSQLDialect"); jpaProperties.put("hibernate.show_sql",true); jpaProperties.put("hibernate.format_sql","false"); jpaProperties.put("hibernate.hbm2ddl.auto","update"); em.setJpaProperties(jpaProperties); return em; } @Bean(name = "jpaTransactionManager") public JpaTransactionManager getJpaTransactionManager() { JpaTransactionManager jpa = new JpaTransactionManager(); jpa.setEntityManagerFactory(getLocalContainerEntityManagerFactoryBean().getNativeEntityManagerFactory()); return jpa; } /* Quartz scheduling configuration */ /** * <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean"> */ @Bean(name = "simpleTrigger") public SimpleTriggerFactoryBean getSimpleTriggerFactoryBean() { SimpleTriggerFactoryBean stfb = new SimpleTriggerFactoryBean(); stfb.setJobDetail(getSimpleQuartzJob().getObject()); stfb.setRepeatInterval(1000); stfb.setStartDelay(1000); return stfb; } /** * <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> */ @Bean(name = "cronTrigger") public CronTriggerFactoryBean getCronTriggerFactoryBean() { CronTriggerFactoryBean ctfb = new CronTriggerFactoryBean(); ctfb.setJobDetail(getQuartzCronJob().getObject()); ctfb.setCronExpression("0/30 * * * * ?"); return ctfb; } /** * <bean id="simpleQuartzJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> */ @Bean(name = "simpleQuartzJob") public MethodInvokingJobDetailFactoryBean getSimpleQuartzJob() { MethodInvokingJobDetailFactoryBean factoryBean = new MethodInvokingJobDetailFactoryBean(); factoryBean.setTargetBeanName("simpleQuartzTask"); factoryBean.setTargetMethod("simpleTaskMethod"); return factoryBean; } /** * <bean id="quartzCronJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> */ @Bean(name = "quartzCronJob") public MethodInvokingJobDetailFactoryBean getQuartzCronJob() { MethodInvokingJobDetailFactoryBean factoryBean = new MethodInvokingJobDetailFactoryBean(); factoryBean.setTargetBeanName("cronQuartzTask"); factoryBean.setTargetMethod("cronTaskMethod"); return factoryBean; } /** * <bean id="simpleQuartzTask" class="ru.javastudy.mvcHtml5Angular.mvc.quartz.QuartzTask" /> */ @Bean(name = "simpleQuartzTask") public QuartzTask getSimpleQuartzTask() { return new QuartzTask(); } /** * <bean id="cronQuartzTask" class="ru.javastudy.mvcHtml5Angular.mvc.quartz.CronQuartzTask" /> */ @Bean(name = "cronQuartzTask") public CronQuartzTask getCronQuartzTask() { return new CronQuartzTask(); } /** * <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> */ @Bean(name = "schedulerFactoryBean") public SchedulerFactoryBean getSchedulerFactoryBean() { SchedulerFactoryBean scheduler = new SchedulerFactoryBean(); scheduler.setTriggers(getSimpleTriggerFactoryBean().getObject(), getCronTriggerFactoryBean().getObject()); return scheduler ; } } |
Как обычно разобьем оба файла на части.
4.1. context:property-placeholder location = «classpath:util.properties»
1 |
<context:property-placeholder location="classpath:util.properties" /> |
и
1 2 3 4 5 6 7 |
@PropertySource(value = "classpath:util.properties") public class ApplicationConfig { @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } |
4.2. bean id = «dataSource» class = «org.springframework.jdbc.datasource.DriverManagerDataSource»
1 2 3 4 5 6 7 8 9 10 11 12 |
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.hsqldb.driverClass}" /> <property name="url" value="${jdbc.hsqldb.url}" /> <property name="username" value="${jdbc.hsqldb.username}" /> <property name="password" value="${jdbc.hsqldb.password}" /> </bean> <!-- initialize Embedded DataSource. Встроенная база данных--> <jdbc:initialize-database data-source="dataSource"> <jdbc:script location="classpath:dbschema.sql"/> <jdbc:script location="classpath:test-data.sql"/> </jdbc:initialize-database> |
и
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
@Value("${jdbc.hsqldb.driverClass}") private String driverClass; @Value("${jdbc.hsqldb.url}") private String jdbcUrl; @Value("${jdbc.hsqldb.username}") private String jdbcUserName; @Value("${jdbc.hsqldb.password}") private String jdbcPassword; @Value("classpath:dbschema.sql") private Resource dbschemaSqlScript; @Value("classpath:test-data.sql") private Resource testDataSqlScript; /** * <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> */ @Bean(name = "dataSource") public DriverManagerDataSource getDriverManagerDataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(driverClass); dataSource.setUrl(jdbcUrl); dataSource.setUsername(jdbcUserName); dataSource.setPassword(jdbcPassword); return dataSource; } /** * <jdbc:initialize-database data-source="dataSource"> * initialize Embedded DataSource. Встроенная база данных */ @Bean public DataSourceInitializer dataSourceInitializer() { final DataSourceInitializer initializer = new DataSourceInitializer(); initializer.setDataSource(getDriverManagerDataSource()); initializer.setDatabasePopulator(getDatabasePopulator()); return initializer; } private DatabasePopulator getDatabasePopulator() { final ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); populator.addScript(dbschemaSqlScript); populator.addScript(testDataSqlScript); return populator; } |
4.3. bean id = «mailSender» class = «org.springframework.mail.javamail.JavaMailSenderImpl»>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="username" value="${java.mail.username}"/> <property name="password" value="${java.mail.password}"/> <property name="port" value="465"/> <property name="javaMailProperties"> <props> <prop key="mail.smtp.auth">true</prop> <prop key="mail.smtp.starttls.enable">true</prop> <prop key="mail.smtp.starttls.required">true</prop> <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop> <prop key="mail.smtp.host">${java.mail.host}</prop> </props> </property> </bean> <!-- Velocity Email Template Config Bean --> <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean"> <property name="resourceLoaderPath" value="/WEB-INF/email-templates/"/> </bean> |
в java config это записывается как:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
@Value("${java.mail.username}") String mailUsername; @Value("${java.mail.password}") String mailPassword; @Value("${java.mail.host}") String mailHost; /** * <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> */ @Bean(name = "mailSender") public JavaMailSenderImpl getJavaMailSender() { JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl(); javaMailSender.setUsername(mailUsername); javaMailSender.setPassword(mailPassword); javaMailSender.setPort(465); Properties javaMailProperties = new Properties(); javaMailProperties.put("mail.smtp.auth", true); javaMailProperties.put("mail.smtp.starttls.enable", true); javaMailProperties.put("mail.smtp.starttls.required", true); javaMailProperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); javaMailProperties.put("mail.smtp.host", mailHost); javaMailSender.setJavaMailProperties(javaMailProperties); return javaMailSender; } /** * <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean"> */ @Bean(name = "velocityEngine") public VelocityEngineFactoryBean getVelocityEngineFactoryBean() { VelocityEngineFactoryBean bean = new VelocityEngineFactoryBean(); bean.setResourceLoaderPath("/WEB-INF/email-templates/"); return bean; } |
4.4. bean id = «restTemplate» class = «org.springframework.web.client.RestTemplate»
1 |
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/> |
или
1 2 3 4 |
@Bean(name = "restTemplate") public RestTemplate getRestTemplate() { return new RestTemplate(); } |
4.5. bean id = «entityManagerFactory» class = «org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean»
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" > <!--packagesToScan - search Entity and mapping them --> <property name="packagesToScan"> <list> <value>ru.javastudy.mvcHtml5Angular.mvc.bean</value> <value>ru.javastudy.mvcHtml5Angular.mvc.rest.model</value> </list> </property> <property name="dataSource" ref="dataSource" /> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" > <property name="generateDdl" value="true" /> <property name="showSql" value="true" /> </bean> </property> <property name="jpaProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">false</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> </bean> <!-- Automatic Transaction Participation--> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> |
и
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
@Bean(name = "entityManagerFactory") public LocalContainerEntityManagerFactoryBean getLocalContainerEntityManagerFactoryBean() { LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setPackagesToScan(new String[] {"ru.javastudy.mvcHtml5Angular.mvc.bean","ru.javastudy.mvcHtml5Angular.mvc.rest.model"}); em.setDataSource(getDriverManagerDataSource()); JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); ((HibernateJpaVendorAdapter)vendorAdapter).setGenerateDdl(true); ((HibernateJpaVendorAdapter)vendorAdapter).setShowSql(true); em.setJpaVendorAdapter(vendorAdapter); Properties jpaProperties = new Properties(); jpaProperties.put("hibernate.dialect","org.hibernate.dialect.HSQLDialect"); jpaProperties.put("hibernate.show_sql",true); jpaProperties.put("hibernate.format_sql","false"); jpaProperties.put("hibernate.hbm2ddl.auto","update"); em.setJpaProperties(jpaProperties); return em; } @Bean(name = "jpaTransactionManager") public JpaTransactionManager getJpaTransactionManager() { JpaTransactionManager jpa = new JpaTransactionManager(); jpa.setEntityManagerFactory(getLocalContainerEntityManagerFactoryBean().getNativeEntityManagerFactory()); return jpa; } |
4.6. task:annotation-driven
1 |
<task:annotation-driven/> |
Эта же запись в java коде
1 2 |
@EnableScheduling //task:annotation-driven public class ApplicationConfig { |
4.7. Scheduling, Quartz, Cron
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<bean id="simpleQuartzJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="simpleQuartzTask" /> <property name="targetMethod" value="simpleTaskMethod" /> </bean> <!-- Quartz cron job --> <bean id="quartzCronJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="cronQuartzTask" /> <property name="targetMethod" value="cronTaskMethod" /> </bean> <!-- Quartz simple task --> <bean id="simpleQuartzTask" class="ru.javastudy.mvcHtml5Angular.mvc.quartz.QuartzTask" /> <!-- Quartz cron task --> <bean id="cronQuartzTask" class="ru.javastudy.mvcHtml5Angular.mvc.quartz.CronQuartzTask" /> <!-- Quartz Scheduler --> <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="jobDetails"> <list> <ref bean="simpleQuartzJob" /> <ref bean="quartzCronJob" /> </list> </property> <property name="triggers"> <list> <ref bean="simpleTrigger" /> <ref bean="cronTrigger" /> </list> </property> </bean> <!-- ScheduleTask example. Use <context:component-scan base-package="ru.javastudy.mvcHtml5Angular.mvc.scheduling"/> and @Component on ru.javastudy.mvcHtml5Angular.mvc.scheduling.ScheduleTask or <bean id="scheduleTask" class="ru.javastudy.mvcHtml5Angular.mvc.scheduling.ScheduleTask"/> --> |
для java конфигурации
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
@Bean(name = "simpleTrigger") public SimpleTriggerFactoryBean getSimpleTriggerFactoryBean() { SimpleTriggerFactoryBean stfb = new SimpleTriggerFactoryBean(); stfb.setJobDetail(getSimpleQuartzJob().getObject()); stfb.setRepeatInterval(1000); stfb.setStartDelay(1000); return stfb; } /** * <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> */ @Bean(name = "cronTrigger") public CronTriggerFactoryBean getCronTriggerFactoryBean() { CronTriggerFactoryBean ctfb = new CronTriggerFactoryBean(); ctfb.setJobDetail(getQuartzCronJob().getObject()); ctfb.setCronExpression("0/30 * * * * ?"); return ctfb; } /** * <bean id="simpleQuartzJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> */ @Bean(name = "simpleQuartzJob") public MethodInvokingJobDetailFactoryBean getSimpleQuartzJob() { MethodInvokingJobDetailFactoryBean factoryBean = new MethodInvokingJobDetailFactoryBean(); factoryBean.setTargetBeanName("simpleQuartzTask"); factoryBean.setTargetMethod("simpleTaskMethod"); return factoryBean; } /** * <bean id="quartzCronJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> */ @Bean(name = "quartzCronJob") public MethodInvokingJobDetailFactoryBean getQuartzCronJob() { MethodInvokingJobDetailFactoryBean factoryBean = new MethodInvokingJobDetailFactoryBean(); factoryBean.setTargetBeanName("cronQuartzTask"); factoryBean.setTargetMethod("cronTaskMethod"); return factoryBean; } /** * <bean id="simpleQuartzTask" class="ru.javastudy.mvcHtml5Angular.mvc.quartz.QuartzTask" /> */ @Bean(name = "simpleQuartzTask") public QuartzTask getSimpleQuartzTask() { return new QuartzTask(); } /** * <bean id="cronQuartzTask" class="ru.javastudy.mvcHtml5Angular.mvc.quartz.CronQuartzTask" /> */ @Bean(name = "cronQuartzTask") public CronQuartzTask getCronQuartzTask() { return new CronQuartzTask(); } /** * <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> */ @Bean(name = "schedulerFactoryBean") public SchedulerFactoryBean getSchedulerFactoryBean() { SchedulerFactoryBean scheduler = new SchedulerFactoryBean(); scheduler.setTriggers(getSimpleTriggerFactoryBean().getObject(), getCronTriggerFactoryBean().getObject()); return scheduler ; } |
Другие части перехода с xml на Java конфигурацию
Spring MVC Java Config (конфигурация с аннотациями) для web.xml
Spring MVC Java Config (конфигурация с аннотациями) для mvc-config.xml
Spring MVC Java Config (конфигурация с аннотациями) для Spring Security (security-config.xml)
Исходный код
23. Annotations config — проект в IDEA
16