spring转springboot后,使用注解方式配置spring相关配置

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();
    }

}


转载,请记名出处

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值