spring轉springboot後,使用註解方式配置spring相關配置
阿新 • • 發佈:2018-11-10
spring專案轉springboot專案後,一般只需要配置yml相關的屬性就可以;當是有時候需要一些比較複雜的配置就需要使用bean註解方式來配置;
1.. 將spring相關的xml 中的bean物件進行注入:
直接上程式碼:yml配置就不給出了
spring.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans default-lazy-init="false" xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd" xmlns:aop="http://www.springframework.org/schema/aop"> <!--業務Beans, 使用註解方式配置--> <context:component-scan base-package="com.yihu.hos"> </context:component-scan> <!--====================返回為null的時候轉“”==========================--> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="com.fasterxml.jackson.databind.ObjectMapper"> <property name="serializationInclusion"> <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value> </property> </bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!--Hibernate 資料庫配置--> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://192.168.1.220:8066/global_db?useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="hos"/> <property name="password" value="123456"/> <property name="initialSize" value="1"/> <property name="maxTotal" value="100"/> <property name="maxIdle" value="50"/> <property name="minIdle" value="20"/> <property name="validationQuery" value="SELECT 1"/> <property name="testOnBorrow" value="true"/> <property name="removeAbandonedTimeout" value="55"/> </bean> <bean id="cacheIntercepter" class="com.yihu.hos.interceptor.AuditInterceptor" /> <!--Hibernate 會話管理器配置--> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="entityInterceptor"> <ref bean="cacheIntercepter"/> </property> <property name="packagesToScan"> <list> <!-- 可以加多個包 --> <value>com.yihu.hos.*.model</value> </list> </property> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.show_sql=false hibernate.format_sql=true </value> </property> <property name="mappingLocations"> <list> <!-- <value>classpath:hbm/*.hbm.xml</value>--> <value>classpath:resource/*.hbm.xml</value> </list> </property> </bean> <!-- 將多個配置檔案讀取到容器中,交給Spring管理 --> <!--Hibernate 事務配置--> <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"/> <!--檔案上傳支援--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/> <!--國際化配置--> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <description>Message Sources</description> <property name="basenames"> <list> <value>text/message</value> </list> </property> <property name="defaultEncoding" value="UTF-8"/> </bean> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"> <property name="cookieMaxAge" value="604800"/> <property name="defaultLocale" value="zh_CN"/> <property name="cookieName" value="Language"></property> </bean> <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> <!--Hibernate模版配置 --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!--<bean id="quartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" scope="singleton">--> <!--<property name="dataSource" ref="dataSource"/>--> <!--<property name="configLocation" value="classpath:/config/quartz.properties" />--> <!--<property name="autoStartup" value="true"/>--> <!--</bean>--> </beans>
j轉換後的ava 配置類:
package com.yihu.hos.config; import com.yihu.hos.interceptor.AuditInterceptor; import org.apache.commons.dbcp2.BasicDataSource; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.bind.RelaxedPropertyResolver; import org.springframework.context.ApplicationContextException; import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.core.env.Environment; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.orm.hibernate4.HibernateTemplate; import org.springframework.orm.hibernate4.HibernateTransactionManager; import org.springframework.orm.hibernate4.LocalSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.i18n.CookieLocaleResolver; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import java.sql.SQLException; import java.util.Arrays; import java.util.Locale; import java.util.Map; import java.util.Properties; /** * @author HZY * @vsrsion 1.0 * Created at 2016/8/5. */ @Configuration @EnableTransactionManagement @ComponentScan("com.yihu.hos") //@ImportResource({"classpath:spring/applicationContext.xml"}) //applicationContext相關bean建立 public class BeanConfig implements EnvironmentAware { // @Autowired // BasicDataSource dataSource; @Value("${spring.jpa.hibernate.dialect}") private String dialect; @Value("${spring.jpa.format-sql}") private String formatSql; @Value("${spring.jpa.show-sql}") private String showSql; private Environment environment; private Map<String , Object> hibernatePropertyResolver; private Map<String , Object> datasourcePropertyResolver; //從application.yml中讀取資源 @Override public void setEnvironment(Environment environment) { this.environment = environment; datasourcePropertyResolver = new RelaxedPropertyResolver(environment).getSubProperties("spring.datasource."); this.hibernatePropertyResolver = new RelaxedPropertyResolver(environment).getSubProperties("spring.jpa."); } //sessionFactory // @Bean // public LocalSessionFactoryBean sessionFactory() throws SQLException { // LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean(); // localSessionFactoryBean.setDataSource(this.dataSource); // Properties properties1 = new Properties(); // properties1.setProperty("hibernate.dialect",hibernatePropertyResolver.get("hibernate.dialect").toString()); // properties1.setProperty("hibernate.show_sql",hibernatePropertyResolver.get("show-sql").toString()); // properties1.setProperty("hibernate.format_sql",hibernatePropertyResolver.get("format-sql").toString()); // localSessionFactoryBean.setHibernateProperties(properties1); // localSessionFactoryBean.setPackagesToScan("com.yihu.hos.*.model"); // ResourceLoader resourceLoader = new DefaultResourceLoader(); // Resource resource = resourceLoader.getResource("classpath:resource/"); // localSessionFactoryBean.setMappingDirectoryLocations(resource); //// localSessionFactoryBean.setPackagesToScan("*"); // return localSessionFactoryBean; // } @Bean public LocalSessionFactoryBean sessionFactory() { LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean(); localSessionFactoryBean.setDataSource(dataSource()); Properties properties1 = new Properties(); properties1.setProperty("hibernate.dialect",dialect); properties1.setProperty("hibernate.show_sql", showSql); properties1.setProperty("hibernate.format_sql",formatSql); localSessionFactoryBean.setHibernateProperties(properties1); localSessionFactoryBean.setPackagesToScan("com.yihu.hos.*.model"); ResourceLoader resourceLoader = new DefaultResourceLoader(); Resource resource = resourceLoader.getResource("resource/"); localSessionFactoryBean.setMappingDirectoryLocations(resource); //設定攔截器 localSessionFactoryBean.setEntityInterceptor(this.auditInterceptor()); return localSessionFactoryBean; } @Bean( destroyMethod = "close") public BasicDataSource dataSource() { if (StringUtils.isEmpty(datasourcePropertyResolver.get("url").toString())) { System.out.println("Your database connection pool configuration is incorrect!" + " Please check your Spring profile, current profiles are:"+ Arrays.toString(environment.getActiveProfiles())); throw new ApplicationContextException( "Database connection pool is not configured correctly"); } BasicDataSource dataSource = new BasicDataSource(); dataSource.setUrl(datasourcePropertyResolver.get("url").toString()); dataSource.setUsername(datasourcePropertyResolver.get("username").toString()); dataSource.setPassword(datasourcePropertyResolver.get("password").toString()); dataSource.setInitialSize((Integer)datasourcePropertyResolver.get("initial-size")); dataSource.setMaxTotal((Integer)datasourcePropertyResolver.get("max-total")); dataSource.setMinIdle((Integer)datasourcePropertyResolver.get("min-idle")); dataSource.setMaxIdle((Integer)datasourcePropertyResolver.get("max-idle")); dataSource.setValidationQuery(datasourcePropertyResolver.get("validation-query").toString()); dataSource.setRemoveAbandonedTimeout(55); dataSource.setTestOnBorrow((boolean)datasourcePropertyResolver.get("test-on-borrow")); return dataSource; } //txManager事務開啟 @Bean public HibernateTransactionManager txManager() throws SQLException { HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager(); LocalSessionFactoryBean sessionFactoryBean = this.sessionFactory(); hibernateTransactionManager.setSessionFactory(sessionFactoryBean.getObject()); return hibernateTransactionManager; } //文經上傳 @Bean public CommonsMultipartResolver multipartResolver(){ return new CommonsMultipartResolver(); } //國際化配置 @Bean public ResourceBundleMessageSource messageSource(){ ResourceBundleMessageSource messageSource =new ResourceBundleMessageSource(); messageSource.setBasenames("text/message"); messageSource.setDefaultEncoding("UTF-8"); return messageSource; } @Bean public CookieLocaleResolver localeResolver(){ CookieLocaleResolver localeResolver = new CookieLocaleResolver(); localeResolver.setCookieName("Language"); localeResolver.setCookieMaxAge(604800); localeResolver.setDefaultLocale(new Locale("zh_CN")); return localeResolver; } @Bean public LocaleChangeInterceptor localeChangeInterceptor(){ return new LocaleChangeInterceptor(); } @Bean public JdbcTemplate jdbcTemplate(){ JdbcTemplate jdbcTemplate = new JdbcTemplate(); try { jdbcTemplate.setDataSource(this.dataSource()); jdbcTemplate.setLazyInit(false); } catch (Exception e) { e.printStackTrace(); } return jdbcTemplate; } //Hibernate模版配置 @Bean public HibernateTemplate hibernateTemplate() throws SQLException { HibernateTemplate hibernateTemplate = new HibernateTemplate(); LocalSessionFactoryBean sessionFactory = this.sessionFactory(); hibernateTemplate.setSessionFactory(sessionFactory.getObject()); return hibernateTemplate; } @Bean public AuditInterceptor auditInterceptor(){ return new AuditInterceptor(); } }