在SpringBoot中的应用
凡注册到Spring容器内的bean,实现了EnvironmentAware接口重写setEnvironment方法后,在工程启动时可以获得application.properties的配置文件配置的属性值。
demo演示
直接上代码,比如我的application.properties文件有如下配置(这里说明一下SpringBoot应用默认的配置文件名就叫做application.properties,可以直接放在当前项目的根目录下,或者一个名叫config的子目录下)
project.name=myproject
再建一个类实现EnvironmentAware接口,其中@Configuration注解在SpringBoot里面相当于Spring的XML文件里的beans标签一样,而@Bean注解相当于XML文件里的bean标签,代表该类会被加载到Spring的IOC容器内。具体代码如下
/** * * * @ClassName MyProjectc.java * @author 沉鱼 * @date 2017年11月28日 下午4:35:39 */ @Configuration public class MyProjectc implements EnvironmentAware { @Override public void setEnvironment(Environment environment) { String projectName = environment.getProperty("project.name"); System.out.println(projectName); } }
启动SpringBoot后,在控制台会打印
@SpringBootApplication public class Application { public static void main(string[] args){ SpringApplication app = new SpringApplication(Application.class app.run(args); } 2017-11-28 18:46.28.003 INFO 7932 --- Tost-startStop-11 o.s.b.w.servlet.Filter 2017-11-28 15:46:28.003 INFO 7932 --- [ost-startStop-1 o.s.b.w.servlet.filter 2017-11-有 18:46:28.003 INFO 7932 --- Tost-startStop-17 o.s.b.w.servlet.filter myproject 2017-11-28 18:46:28.392 INFO 7932 --- [ main] s.w.s.m.m.a.RequestMap
具体SpirngBoot整合Mybatis应用
application.properties文件配置
datasource.driverClassName=com.mysql.jdbc.Driver datasource.url=jdbc:mysql://localhost:3306/myproject?characterEncoding=utf8&serverTimezone=UTC datasource.username=chenyu datasource.password=123456
具体javaConfig代码
@Configuration public class MyBatisConfig implements EnvironmentAware { private Environment environment; @Override public void setEnvironment(final Environment environment) { this.environment = environment; } /** * 创建数据源(数据源的名称:方法名可以取为XXXDataSource(),XXX为数据库名 称,该名称也就是数据源的名称) */ @Bean public DataSource druidDataSource() throws Exception { Properties props = new Properties(); props.put("driverClassName", environment.getProperty("datasource.driverClassName")); props.put("url", environment.getProperty("datasource.url")); props.put("username", environment.getProperty("datasource.username")); props.put("password", environment.getProperty("datasource.password")); return DruidDataSourceFactory.createDataSource(props); } /** * 根据数据源创建SqlSessionFactory */ @Bean public SqlSessionFactory sqlSessionFactory() throws Exception { PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); SqlSessionFactoryBean fb = new SqlSessionFactoryBean(); // 指定数据源(这个必须有,否则报错) fb.setDataSource(druidDataSource()); fb.setTypeAliasesPackage("com.tf56.pushService.dal.domain"); // 指定mapper文件 fb.setMapperLocations(resolver.getResources("classpath:mapper/*.xml")); return fb.getObject(); } }