spring boot前传(二):读取外部资源文件

通过@PropertySource可以指定读取的配置文件,通过@Value注解获取值,具体用法见案例代码中的注释!

这里我们以初始化数据源dataSource为例来演示

工程目录

spring boot前传(二):读取外部资源文件_第1张图片

阿里巴巴开源的Durid数据源配置文件

=========================druidConfig.properties================================

driverClassName=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/schooldb
duridUserName=root
password=123456
#配置监控统计拦截的filters,去掉后监控界面sql无法统计
filters=stat
#配置初始化大小 
initialSize=6
#配置初始化最大连接数 
maxActive=20
#配置最小空闲连接数 
minIdle=3
#配置获取连接等待超时的时间,1分钟 
maxWait=60000
#检测连接是否有效的SQL 
validationQuery=SELECT 'x'
#申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效 
testWhileIdle=true
#申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能 
testOnBorrow=false
#归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能 
testOnReturn=false
#启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true 
maxPoolPreparedStatementPerConnectionSize=20
#对于长时间不使用的连接强制关闭 
removeAbandoned=true
#超过30秒的空闲连接就可以被关闭了,单位是秒 
removeAbandonedTimeout=30
#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 
timeBetweenEvictionRunsMillis=10000
#配置一个连接在池中最小生存的时间,单位是毫秒 
minEvictableIdleTimeMillis=30000
配置类

===============================SpringConfig.java=========================

package com.wx.config;

import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import com.alibaba.druid.pool.DruidDataSource;
import com.wx.dao.IUserDao;
import com.wx.dao.UserDaoImpl;

//通过该注解来表明该类是一个Spring的配置,相当于一个传统的ApplicationContext.xml
@Configuration
// 相当于配置文件里面的标签
@ComponentScan(basePackages = "com.wx.dao,com.wx.biz")
//@PropertySource用来读取外部资源文件
//ignoreResourceNotFound表示忽略没读到的资源文件
@PropertySource(value = { "classpath:druidConfig.properties",
		"classpath:jdbc.properties" }, ignoreResourceNotFound = true)
public class SpringConfig {
	//Value注解用来获取属性的值
	@Value("${driverClassName}")
	private String driverClassName;
	@Value("${url}")
	private String url;
	@Value("${duridUserName}")
	private String username;
	@Value("${password}")
	private String password;
	@Value("${filters}")
	private String filters;
	@Value("${initialSize}")
	private int initialSize;
	@Value("${maxActive}")
	private int maxActive;
	@Value("${minIdle}")
	private int minIdle;
	@Value("${maxWait}")
	private int maxWait;
	@Value("${validationQuery}")
	private String validationQuery;
	@Value("${testWhileIdle}")
	private boolean testWhileIdle;
	@Value("${testOnBorrow}")
	private boolean testOnBorrow;
	@Value("${testOnReturn}")
	private boolean testOnReturn;
	@Value("${maxPoolPreparedStatementPerConnectionSize}")
	private int maxPoolPreparedStatementPerConnectionSize;
	@Value("${removeAbandoned}")
	private boolean removeAbandoned;
	@Value("${removeAbandonedTimeout}")
	private int removeAbandonedTimeout;
	@Value("${timeBetweenEvictionRunsMillis}")
	private int timeBetweenEvictionRunsMillis;
	@Value("${minEvictableIdleTimeMillis}")
	private int minEvictableIdleTimeMillis;
	
	@Bean(initMethod="init",destroyMethod="close")
	public DruidDataSource dataSource(){
		DruidDataSource dataSource=new DruidDataSource();
		try {
			dataSource.setUrl(url);
			dataSource.setDriverClassName(driverClassName);
			dataSource.setUsername(username);
			dataSource.setPassword(password);
			dataSource.setFilters(filters);
			dataSource.setInitialSize(initialSize);
			dataSource.setMaxActive(maxActive);
			dataSource.setMinIdle(minIdle);
			dataSource.setMaxWait(maxWait);
			dataSource.setValidationQuery(validationQuery);
			dataSource.setTestWhileIdle(testWhileIdle);
			dataSource.setTestOnBorrow(testOnBorrow);
			dataSource.setTestOnReturn(testOnReturn);
			dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
			dataSource.setRemoveAbandoned(removeAbandoned);
			dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
			dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
			dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
			System.out.println("数据源初始化成功!");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return dataSource;
	}
}
特别注意:资源文件中的duridUserName=root   不能写成userName=root,否则会取到操作系统的登录用户名!

pom配置

==========================pom.xml==================================


	4.0.0
	com.wx
	bootpre02
	0.0.1-SNAPSHOT

	
		
			org.springframework
			spring-core
			4.3.3.RELEASE
		
		
			org.springframework
			spring-beans
			4.3.3.RELEASE
		
		
			org.springframework
			spring-context
			4.3.3.RELEASE
		
		
			org.springframework
			spring-expression
			4.3.3.RELEASE
		
		
			log4j
			log4j
			1.2.17
		
		
		
	    com.alibaba
		    druid
		    1.0.9
		
		
	    	mysql
	    	mysql-connector-java
	    5.1.26
	
	
	
		${project.artifactId}
		
			
			
				org.apache.maven.plugins
				maven-resources-plugin
				
					UTF-8
				
			
			
			
				org.apache.maven.plugins
				maven-compiler-plugin
				
					1.7
					1.7
					UTF-8
				
			
		

	



实体类

==============================UserEntity.java=====================

package com.wx.entitys;

import java.io.Serializable;

public class UserEntity implements Serializable {
	private static final long serialVersionUID = 1034088741557780953L;
	private Integer userId;
	private String userName;
	private String passWord;
	private String email;
	
	
	public UserEntity() {
	}
	public UserEntity(String userName, String passWord) {
		super();
		this.userName = userName;
		this.passWord = passWord;
	}
	public Integer getUserId() {
		return userId;
	}
	public void setUserId(Integer userId) {
		this.userId = userId;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassWord() {
		return passWord;
	}
	public void setPassWord(String passWord) {
		this.passWord = passWord;
	}
	
	public void setEmail(String email) {
		this.email = email;
	}
	
	public String getEmail() {
		return email;
	}
}
dao层代码

=========================================UserDaoImpl.java==========================

package com.wx.dao;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.wx.entitys.UserEntity;

@Component("userDao")
public class UserDaoImpl implements IUserDao {
	
	@Autowired
	private DataSource dataSource;
	
	public List queryUserList(){
        List userList = new ArrayList();
        Connection conn=null;
        try {
			conn=dataSource.getConnection();
			PreparedStatement psmt=conn.prepareStatement("select * from users");
			ResultSet rs=psmt.executeQuery();
			UserEntity user=null;
			while(rs.next()){
				user=new UserEntity();
				user.setUserId(rs.getInt("userId"));
				user.setUserName(rs.getString("userName"));
				user.setPassWord(rs.getString("passWord"));
				user.setEmail(rs.getString("email"));
				userList.add(user);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				if(conn!=null){
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
        return userList;
    }

}
业务层代码

=============================UserBiz.java=========================

package com.wx.biz;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.wx.dao.IUserDao;
import com.wx.entitys.UserEntity;

@Service
public class UserBiz {
	//Autowired默认根据类型进行装配,Qualifier根据名称装配
	@Autowired
	@Qualifier("userDao")
	private IUserDao userDao;
	
	public List queryUserList(){
		return userDao.queryUserList();
	}
}

测试类

==================TestConfig01.java==============================

package com.wx.test;

import java.util.List;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.wx.biz.UserBiz;
import com.wx.config.SpringConfig;
import com.wx.entitys.UserEntity;

public class TestConfig01 {
	public static void main(String[] args) {
		//通过java配置来实例化spring容器
		AnnotationConfigApplicationContext ctx=
				new AnnotationConfigApplicationContext(SpringConfig.class);
		//在spring容器中获取bean对象
		//名称userBiz是注解根据类UserBiz自动生成的
		UserBiz userBiz=(UserBiz)ctx.getBean("userBiz");
		//或者采取下面的方式
		//UserBiz userBiz=(UserBiz)ctx.getBean(UserBiz.class);
		List userList=userBiz.queryUserList();
		for(UserEntity user:userList){
			System.out.print(user.getUserId());
			System.out.print("\t"+user.getUserName());
			System.out.print("\t"+user.getPassWord());
			System.out.println("\t"+user.getEmail());
		}
		try {
			Thread.sleep(100000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		//销毁容器
		ctx.destroy();
	}
}
运行结果如下图

spring boot前传(二):读取外部资源文件_第2张图片

可以从sqlyog界面观察数据源是否正常启动

spring boot前传(二):读取外部资源文件_第3张图片

如果本文帮助到了您,请点个赞吧!

你可能感兴趣的:(spring,boot)