spring整理

2018-09-13  本文已影响0人  dotff
1.自定义Filters扫描注解
@ComponentScan( 
    includeFilters = { @ComponentScan.Filter( type = FilterType.REGEX,
        pattern = {"cn.ff.demo.*Dao", "cn.ff.demo.*Service"})
    },
    excludeFilters = { @ComponentScan.Filter( type = FilterType.ANNOTATION,
        classes = {org.springframework.stereotype.Controller.class}) 
    }
)
2.多模块引用其他模块时无法注入bean的问题

例如spring cloud项目中auth模块引用需要common模块。默认只扫描Application路径之下的包,所以需要设置。

  1. 使用@ComponentScan(value="com.xx")注解,指定扫描的包路径。
    但是每个模块都这样很low,所以可以如下:
  2. 在common模块的META-INF/spring.factories文件中配置接口的实现类名称,spring boot会读取这些配置文件并实例化。
    示例:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  cn.ff.common.config.RedisConfig,\
  cn.ff.common.utils.RedisUtil
3. pom中配置多环境及springboot 配置文件使用maven中的变量

在pom中配置多环境:

<profiles>
        <profile>
            <id>dev</id>
            <activation>
                <activeByDefault>true</activeByDefault><!--默认激活配置-->
            </activation>
            <properties>
                <profile.name>dev</profile.name><!--当前环境-->
                <config.server-addr>127.0.0.1:8848</config.server-addr><!--配置中心地址-->
                <discovery.server-addr>127.0.0.1:8848</discovery.server-addr>
                <config.namespace/> <!--配置中心多环境支持的namespace,使用ID默认为空-->
            </properties>
        </profile>
        <profile>
            <id>test</id>
            <properties>
                <profile.name>test</profile.name>
                <config.server-addr>192.168.48.200:8848</config.server-addr>
                <discovery.server-addr>192.168.48.200:8848</discovery.server-addr>
                <config.namespace/>
            </properties>
        </profile>

    </profiles>

指定一个环境: mvn clean install package -P {dev|test|prod}

在springboot中使用pom文件中定义的变量就不能用默认的${}形式,而是用@@

spring:
    application:
        name: gateway
    profiles:
        active: '@profile.name@'    #对应pom中 <profile.name>

如果想用${}的形式 那么就需要在pom的 build 中添加如下

<build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <configuration>
                        <encoding>utf-8</encoding>
                        <useDefaultDelimiters>true</useDefaultDelimiters> <!-- 就是这啦 -->
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
                <resources>
            <!-- 先指定 src/main/resources下所有文件及文件夹为资源文件 -->
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
</build>
上一篇 下一篇

猜你喜欢

热点阅读