spring aop示例

最近,我们介绍了Spring Profiles的概念。

此概念是针对不同部署环境的轻松配置区分符。

直接的用例(已提出)是对相关的类进行注释,以便Spring根据活动的配置文件加载适当的类。

但是,这种方法可能并不总是适用于常见的用例……通常,配置密钥是相同的,并且每个值只会随环境而变化。

在本文中,我想提出一种模式来支持按环境加载配置数据, 无需为每个概要文件(即针对每个环境)创建/维护多个类。

在整个文章中,假设每个部署环境的数据库定义(例如用户名或连接URL)不同,我将以数据库连接配置为例。

主要思想是使用一个类来加载配置(即,一个类用于DB连接定义),然后将适当的实例注入其中,以保存正确的概要文件配置数据。

为了方便和清楚起见,该过程分为三个阶段:

阶段1 :基础设施
步骤1.1 –创建一个包含所有配置数据的属性文件
步骤1.2 –为每个配置文件创建注释 步骤1.3 –确保在上下文加载期间加载了配置文件

阶段2 :实施配置文件模式
步骤2.1 –创建属性界面
步骤2.2 –为每个配置文件创建一个类 步骤2.3 –创建一个包含所有数据的抽象文件

阶段3 :使用模式
步骤3.1 –使用模式的示例

弹簧轮廓图–阶段1:基础准备

此阶段将建立使用Spring Profile和配置文件的初始基础设施。

步骤1.1 –创建一个包含所有配置数据的属性文件

假设您有一个maven风格的项目,请在src / main / resources / properties中为每个环境创建一个文件,例如:

my_company_dev.properties
my_company_test.properties
my_company_production.properties

my_company_dev.properties内容的示例:

jdbc.url = jdbc:mysql:// localhost:3306 / my_project_db
db.username = dev1
db.password = dev1 hibernate.show_sql = true

my_company_production.properties内容的示例:

jdbc.url = jdbc:mysql://10.26.26.26:3306 / my_project_db
db.username = prod1
db.password = fdasjkladsof8aualwnlulw344uwj9l34 hibernate.show_sql = false

步骤1.2 –为每个配置文件创建注释

在src.main.java.com.mycompany.annotation中为每个Profile创建注释,例如:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Profile("DEV")
public @interface Dev {
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Profile("PRODUCTION")
public @interface Production {
}

为每个配置文件创建一个枚举:
公共接口MyEnums {

public enum Profile{
DEV,
TEST,
PRODUCTION
}

步骤1.3 –确保在上下文加载期间加载了配置文件

  • 定义一个系统变量以指示代码在哪个环境中运行。
    在Tomcat中,转到$ {tomcat.di} /conf/catalina.properties并插入一行:
    profile = DEV(根据您的环境)
  • 定义一个类来设置活动配置文件
    public class ConfigurableApplicationContextInitializer implementsApplicationContextInitializer<configurableapplicationcontext> {@Overridepublic void initialize(ConfigurableApplicationContext applicationContext) {String profile = System.getProperty("profile");if (profile==null || profile.equalsIgnoreCase(Profile.DEV.name())){applicationContext.getEnvironment().setActiveProfiles(Profile.DEV.name());   }else if(profile.equalsIgnoreCase(Profile.PRODUCTION.name())){applicationContext.getEnvironment().setActiveProfiles(Profile.PRODUCTION.name()); }else if(profile.equalsIgnoreCase(Profile.TEST.name())){applicationContext.getEnvironment().setActiveProfiles(Profile.TEST.name()); }}
    }
  • 确保在上下文加载期间加载了该类
    在项目web.xml中,插入以下内容:

    <context-param><param-name>contextInitializerClasses</param-name><param-value>com.matomy.conf.ConfigurableApplicationContextInitializer</param-value>
    </context-param>

阶段2:实施配置文件模式

此阶段利用我们之前构建的基础架构并实现配置文件模式。

步骤2.1 –创建属性界面
为您拥有的配置数据创建一个接口。
在我们的情况下,该接口将提供对四个配置数据项的访问。 所以看起来像这样:

public interface SystemStrings {String getJdbcUrl();
String getDBUsername();
String getDBPassword();
Boolean getHibernateShowSQL();
//.....

步骤2.2 –为每个配置文件创建一个类

开发配置文件示例:

@Dev //Notice the dev annotation
@Component("systemStrings")
public class SystemStringsDevImpl extends AbstractSystemStrings implements SystemStrings{public SystemStringsDevImpl() throws IOException {//indication on the relevant properties filesuper("/properties/my_company_dev.properties");}
}

生产资料示例:

@Prouction //Notice the production annotation
@Component("systemStrings")
public class SystemStringsProductionImpl extends AbstractSystemStrings implements SystemStrings{public SystemStringsProductionImpl() throws IOException {//indication on the relevant properties filesuper("/properties/my_company_production.properties");}
}

上面的两个类是属性文件与相关环境之间进行绑定的位置。

您可能已经注意到,这些类扩展了一个抽象类。 这项技术很有用,因此我们不需要为每个Profile定义每个getter,从长远来看,这是无法管理的,实际上,这样做是没有意义的。

蜜糖和蜂蜜位于下一步,其中定义了抽象类。

步骤2.3 –创建一个包含所有数据的抽象文件

public abstract class AbstractSystemStrings implements SystemStrings{//Variables as in configuration properties file
private String jdbcUrl;
private String dBUsername;
private String dBPassword;
private boolean hibernateShowSQL;public AbstractSystemStrings(String activePropertiesFile) throws IOException {//option to override project configuration from externalFileloadConfigurationFromExternalFile();//optional..//load relevant propertiesloadProjectConfigurationPerEnvironment(activePropertiesFile);  }private void loadProjectConfigurationPerEnvironment(String activePropertiesFile) throws IOException {Resource[] resources = new ClassPathResource[ ]  {  new ClassPathResource( activePropertiesFile ) };Properties props = null;props = PropertiesLoaderUtils.loadProperties(resources[0]);jdbcUrl = props.getProperty("jdbc.url");dBUsername = props.getProperty("db.username"); dBPassword = props.getProperty("db.password");hibernateShowSQL = new Boolean(props.getProperty("hibernate.show_sql"));
}//here should come the interface getters....

阶段3:使用模式

您可能还记得,在前面的步骤中,我们定义了一个配置数据接口。

现在,我们将在需要每个环境不同数据的类中使用该接口

请注意,该示例是与Spring博客中给出的示例的主要区别,因为现在我们不需要为每个概要文件创建一个类 ,因为在这种情况下,我们在概要文件中使用相同的方法并且仅改变数据

步骤3.1 –使用模式的示例

@Configuration
@EnableTransactionManagement
//DB connection configuration class
//(don't tell me you're still using xml... ;-)
public class PersistenceConfig {@Autowiredprivate SystemStrings systemStrings; //Spring will wire by active profile@Beanpublic LocalContainerEntityManagerFactoryBean entityManagerFactoryNg(){LocalContainerEntityManagerFactoryBean factoryBean= new LocalContainerEntityManagerFactoryBean();factoryBean.setDataSource( dataSource() );factoryBean.setPersistenceUnitName("my_pu");       JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(){{// JPA propertiesthis.setDatabase( Database.MYSQL);
this.setDatabasePlatform("org.hibernate.dialect.MySQLDialect");this.setShowSql(systemStrings.getShowSqlMngHibernate());//is set per environemnt..           }};       factoryBean.setJpaVendorAdapter( vendorAdapter );factoryBean.setJpaProperties( additionalProperties() );return factoryBean;}
//...
@Beanpublic ComboPooledDataSource dataSource(){ComboPooledDataSource poolDataSource = new ComboPooledDataSource();try {poolDataSource.setDriverClass( systemStrings.getDriverClassNameMngHibernate() );} catch (PropertyVetoException e) {e.printStackTrace();}       //is set per environemnt..poolDataSource.setJdbcUrl(systemStrings.getJdbcUrl());poolDataSource.setUser( systemStrings.getDBUsername() );poolDataSource.setPassword( systemStrings.getDBPassword() );//.. more properties...       return poolDataSource;}
}

我将不胜感激和改进。
请享用!

参考:来自我们JCG合作伙伴 Gal Levinsky的Spring Profile模式,来自Gal Levinsky的博客博客。

翻译自: https://www.javacodegeeks.com/2012/08/spring-profile-pattern-example_7.html

spring aop示例

spring aop示例_Spring Profile模式示例相关推荐

  1. spring aop实践_使用Spring AOP实现活动记录模式

    spring aop实践 在课堂设计过程中,我们应就每个班级的职责分配做出决定. 如果我们选择的不错,系统将更易于理解,维护和扩展. 我们几乎所有的项目都有一个持久层,即关系数据库,文档存储或仅XML ...

  2. 使用Spring AOP实现活动记录模式

    在班级设计中,我们应就每个班级的职责分配做出决定. 如果我们选择的不错,系统将更易于理解,维护和扩展. 几乎我们所有的项目都有一个持久层,即关系数据库,文档存储或仅XML文件. 通常,您将使用DAO模 ...

  3. Spring Profile模式示例

    最近,我们介绍了Spring Profiles的概念. 此概念是针对不同部署环境的轻松配置区分符. 直接的用例(已提出)是对相关类进行注释,以便Spring根据活动的配置文件加载适当的类. 但是,这种 ...

  4. spring aop示例_Spring查找方法示例

    spring aop示例 当一个bean依赖于另一个bean时,我们使用setter属性或通过构造函数注入bean. getter方法将向我们返回已设置的引用,但是假设您每次调用getter方法时都想 ...

  5. spring aop原理_Spring知识点总结!已整理成142页离线文档(源码笔记+思维导图)...

    写在前面 由于Spring家族的东西很多,一次性写完也不太现实.所以这一次先更新Spring[最核心]的知识点:AOP和IOC 无论是入门还是面试,理解AOP和IOC都是非常重要的.在面试的时候,我没 ...

  6. spring boot示例_Spring Boot完成示例

    spring boot示例 这篇文章提供了一个使用Spring Boot开发松耦合的REST服务的完整示例. 使用spring boot,我们可以开发可独立运行的生产就绪的Java应用程序,使其成为独 ...

  7. spring aop设计模式_Spring框架中设计模式的运用

    设计模式大家可能随口就能说出总共有23种,但是具体怎么用,或者在常用的组建中有哪些体现,这时候不一定说的上来了.接下来几篇文章,我们一起深入理解.首先我们一起了解下常用的组建中是怎么运用的,比如 JD ...

  8. spring boot示例_Spring Boot REST示例

    spring boot示例 Spring Boot is an awesome module from Spring Framework. Once you are used to it, then ...

  9. Spring AOP概述及底层实现原理

    Spring AOP概述及底层实现原理 aop概述 AOP全称为Aspect Oriented Programming的缩写,意为:面向切面编程.将程序中公用代码进行抽离,通过动态代理实现程序功能的统 ...

最新文章

  1. 超全大厂Java面试彩蛋
  2. 每天学一点flash (20) flash cs3.0 外部加载图片
  3. stream测试内存_.net core百万设备连接服务和硬件需求测试
  4. 深入理解JavaScript定时函数setTimeout
  5. maven package 知识(转载)
  6. pcm 转化为wav 文件
  7. 组件设计实战--组件之间的关系 (Event、依赖倒置、Bridge)
  8. 数据结构---二叉平衡排序树的删除
  9. poi为什么所有celltype都是string_不是所有向日葵都向阳,你知道为什么吗
  10. 小数点保留若干位小数 %.*f
  11. Azure进阶攻略 | 你的程序也能察言观色?这个真的可以有!
  12. 思科、华为、Dell visio图下载
  13. SmartAdmin开源简单的门户网站管理系统
  14. 企业信息科技安全的三道防线及解决方案
  15. POJ 3126 Prime Path(BFS + 素数打表)
  16. 812计算机专业排名,新鲜出炉2019年美国大学计算机工程专业排名榜单 麻省位居首位!...
  17. android 5.0 pie,Android各版本份额占比出炉:Android Pie仍未知
  18. 新旧电脑数据传输|怎么实现两台电脑硬盘数据传输
  19. java使用cxf调用https方式的webservice
  20. 用IE点击html页面用谷歌打开,如何在电脑中使用谷歌浏览器打开不兼容的网页

热门文章

  1. Java GC系列(4):垃圾回收监视和分析
  2. Oracle入门(十四C)之转换函数
  3. 进入ASP .net mvc的世界
  4. ssm(Spring+Spring mvc+mybatis)Dao层配置sql的文件——DeptDaoMapper.xml
  5. SpringAOP的SchemaBase方式
  6. 转:SparkConf 配置的用法
  7. java批处理 异常处理_Java批处理教程
  8. java parse_Java命令行界面(第9部分):parse-cmd
  9. jpa一级缓存和二级缓存_了解一级JPA缓存
  10. JDK 14中的常规,安全和确定性外部内存访问