SpringBoot初学汇总

SpringBoot基于Spring的项目搭建框架,相较于Spring简化了配置而已

SpringBoot的核心:

    自动配置:针对很多Spring应用程序常见的应用功能,Spring Boot能自动提供相关配置

    起步依赖:告诉Spring Boot需要什么功能,它就能引入需要的库。

    命令行界面:这是Spring Boot的可选特性,借此你只需写代码就能完成完整的应用程序,无需传统项目构建。

    Actuator:让你能够深入运行中的Spring Boot应用程序,一探究竟。

由于我项目的原因,命令行界面和Actuator未曾涉及。示例项目采用框架SpringBoot+jpa ,项目管理采用gradle

1. 首先就项目,看SpringBoot的核心特点:

build.gradle的配置文件

从配置文件中可以看到,jar包的依赖方式为,是因为SpringBoot将常用的jar包进行了功能性的分类,你需要什么功能,秩序配置上功能,SpringBoot会自定将改功能需要的jar包依赖进来(起步依赖),并根据你配置的功能自动进行配置(自动配置)

 
 
compile('org.springframework.boot:spring-boot-starter-data-redis')
buildscript {
	ext {
		springBootVersion = '2.1.0.BUILD-SNAPSHOT'
	}
	repositories {
		mavenCentral()
		maven { url "https://repo.spring.io/snapshot" }
		maven { url "https://repo.spring.io/milestone" }
	}
	dependencies {
		classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
	}
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
	mavenCentral()
	maven { url "https://repo.spring.io/snapshot" }
	maven { url "https://repo.spring.io/milestone" }
}


dependencies {
	compile('org.springframework.boot:spring-boot-starter-data-mongodb')
	compile('org.springframework.boot:spring-boot-starter-data-redis')
	compile('org.springframework.boot:spring-boot-starter-data-jpa')
	compile('org.springframework.boot:spring-boot-starter-jdbc')
	compile('org.springframework.boot:spring-boot-starter-aop')

//	compile('org.springframework.boot:spring-boot-starter-security')
	compile('org.springframework.boot:spring-boot-starter-web')
//	compile('org.springframework.cloud:spring-cloud-starter-oauth2')
	compile('com.alibaba:druid-spring-boot-starter:1.1.9')
	compile('com.alibaba:fastjson:1.2.3')
	compile fileTree(dir:'libs',include:['*.jar'])
	runtime('mysql:mysql-connector-java')
	compile('org.projectlombok:lombok:1.16.20')
	compile('commons-lang:commons-lang:2.5')
	compile('org.springframework.boot:spring-boot-configuration-processor')
	compile('commons-lang:commons-lang:2.5')
//	providedRuntime('org.springframework.boot:spring-boot-starter-tomcat')




	testCompile('org.springframework.boot:spring-boot-starter-test')
	testCompile('org.springframework.security:spring-security-test')
}

2.SpringBoot特有的配置文件.yml文件

    SpringBoot的项目在创建的时候,会在根目录下自动生成一个 项目名.java 的文件,启动项目只需要运行改java文件的main方法即可,因为SpringBoot有自己内置的Tomcat(具体有哪些,可自行百度)等web容器,而容器的监听端口和ip可以在.yml中配置,.yml文件还包含jdk的编译版本,编码等。

#spring:
#  profiles:
#    active: ${SPRING_PROFILES_ACTIVE:dev}
#  application:
#      name: auth-server
#
#  jpa:
#    open-in-view: true
#    database: POSTGRESQL
#    show-sql: true
#    hibernate:
#      ddl-auto: update
#  datasource:
#    platform: postgres
#    url: jdbc:postgresql://192.168.1.140:5432/auth
#    username: wang
#    password: yunfei
#    driver-class-name: org.postgresql.Driver
#  redis:
#    host: 192.168.1.140

server:
  port: 9999
  address: 127.0.0.1

# SPRING PROFILES
spring:
    # HTTP ENCODING
    http:
        encoding.charset: UTF-8
        encoding.enable: true
        encoding.force: true
#    mvc:
#        view.prefix: /jsp/
#        view.suffix: .jsp
    #jpa配置
#    jpa:
#        database: mysql
#        generate-ddl: true
#        show-sql: true
#        hibernate:
#          ddl-auto: update
#          naming:
#            physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy


logging.level.org.springframework.security: DEBUG

logging.leve.org.springframework: DEBUG

2. SpringBoot应用

    SpringBoot即可根据依赖jar包进行配置,还能够手动进行配置,不过配置的方式为注解。

package com.example.gradle_boot.conf;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

/**
 * Created by ding on 2018/4/17.
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerFactoryPri",
        transactionManagerRef="priTransactionManager",
        basePackages= { "com.example.gradle_boot.mapper.primary" }) //设置Repository所在位置 //fixme
public class PrimaryDataSource {

    @Autowired
    @Qualifier("priDataSource")
    private DataSource priDataSource;
    @Primary
    @Bean(name = "entityManagerPri")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryPri(builder).getObject().createEntityManager();
    }
    @Primary
    @Bean(name = "entityManagerFactoryPri")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPri (EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(priDataSource)
                .properties(getVendorProperties())
                .packages("com.example.gradle_boot.entity.primary") //设置实体类所在位置
                .persistenceUnit("priPersistenceUnit")
                .build();
    }

    @Autowired
    private JpaProperties jpaProperties;

    private Map<String, Object> getVendorProperties() {
        return jpaProperties.getHibernateProperties(new HibernateSettings());
    }

    /**
     * 配置事物管理器
     * @return
     */
    @Bean(name = "priTransactionManager")
    @Primary
    public PlatformTransactionManager writeTransactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryPri(builder).getObject());
    }
}

DataSource的配置:EnableJpaRepositories注解的basePackage指定的是repostoy的包名,这样在扫描注解的时候才能扫描到,但是当不用框架查询直接用template查询的时候,直接注入即可,该basePackage不配置也可。

package com.example.gradle_boot.conf;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by ding on 2018/4/17.
 */
@Configuration
public class SpringConfigration {
    @Primary
    @Bean(name="priDataSource")
    @Qualifier("priDataSource")
    @ConfigurationProperties("spring.datasource.primary")
    public DataSource dataSourcePri(){
        System.out.println(" Primary mysql datasource 初始化...");
        return DruidDataSourceBuilder.create().build();
    }


    @Bean(name="auxDataSource")
    @Qualifier("auxSource")
    @ConfigurationProperties("spring.datasource.auxiliary")
    public DataSource dataSourceAux(){
        System.out.println(" Auxiliary mysql datasource 初始化...");
        return DruidDataSourceBuilder.create().build();
    }

    //mongo 多数据源配置
    @Autowired
    private MultipleMongoProperties mongoProperties;

    @Primary
    @Bean(name = PrimaryMongoConfig.MONGO_TEMPLATE)
    public MongoTemplate primaryMongoTemplate() throws Exception {
        System.out.println(" mongo primary 初始化...");
        return new MongoTemplate(primaryFactory(this.mongoProperties.getPrimary()));
    }


    @Bean
    @Primary
    public MongoDbFactory primaryFactory(MongoProperties mongo) throws Exception {

        MongoCredential credential = MongoCredential.createScramSha1Credential(mongo.getUsername(), mongo.getDatabase(), mongo.getPassword());
        List<ServerAddress> addresses = new ArrayList<ServerAddress>();
        for(String hosts : mongo.getHost().split(",")) {
            ServerAddress address = new ServerAddress(hosts, mongo.getPort());
            addresses.add(address);
        }
        MongoClient mongoClient = new MongoClient(addresses, Arrays.asList(credential));
        return new SimpleMongoDbFactory(mongoClient,mongo.getDatabase());
    }

    @Bean
    @Qualifier(AuxiliaryMongoConfig.MONGO_TEMPLATE)
    public MongoTemplate auxiliaryMongoTemplate() throws Exception {
        System.out.println(" mongo secondary 初始化...");
        return new MongoTemplate(auxiliaryFactory(this.mongoProperties.getAuxiliary()));
    }

    @Bean
    public MongoDbFactory auxiliaryFactory(MongoProperties mongo) throws Exception {

        MongoCredential credential = MongoCredential.createScramSha1Credential(mongo.getUsername(), mongo.getDatabase(), mongo.getPassword());
        List<ServerAddress> addresses = new ArrayList<ServerAddress>();
        for(String hosts : mongo.getHost().split(",")) {
            ServerAddress address = new ServerAddress(hosts, mongo.getPort());
            addresses.add(address);
        }
        MongoClient mongoClient = new MongoClient(addresses, Arrays.asList(credential));
        return new SimpleMongoDbFactory(mongoClient,mongo.getDatabase());
    }

}
 
 

将dataSource给SpringBoot管理。

我的项目中配置了mysql和mongo的多数据源,但是时在用mongoTample查询的时候注入的队形总是错误的,不能正确的注入mongoTample对象,需要用注解@Qualifier("auxiliaryMongoTemplate")指定bean的名称,才能正常注入










    

    





猜你喜欢

转载自blog.csdn.net/dc_123456/article/details/80253556