参数写到property配置文件

参考文档:Java读取property配置文件的方法


1.建立一个xx.properties文件,放到类同一目录下。

本项目中定义一个url.properties,如下放置:


2.xxl.properties文件中,定义键值对。

例如:db.properties 内容好下:

username=sa

password=sa

url=jdbc:jtds:sqlserver://192.168.0.10:1433/Collection

driver=net.sourceforge.jtds.jdbc.Driver

本项目中url.properties如下:


3.把参数读写到类文件中。通用链接数据库写法如下:

InputStream in = getClass().getResourceAsStream("db.properties");

Properties pro = new Properties();

    try {

    pro.load(in);

    String  username = pro.getProperty("username").trim();

    String  password = pro.getProperty("password").trim();

    String  url = pro.getProperty("url").trim();

    String  driver = pro.getProperty("driver").trim();

    System.out.println(driver);

    Class.forName(driver);

    con = DriverManager.getConnection(url, username, password);

        } catch (IOException e) {

            e.printStackTrace();

        }

在本项目中,如下实现,采用了单例模式。


欧克,完事了。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在HandlerInterceptor获取配置文件参数的方法主要有两种: 1. 通过实现ApplicationContextAware接口,获取ApplicationContext上下文对象,然后使用该对象的getEnvironment()方法获取环境对象,再使用getProperty()方法获取配置文件参数值。 示例代码: ```java public class MyInterceptor implements HandlerInterceptor, ApplicationContextAware { private String myParam; private ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Environment env = applicationContext.getEnvironment(); myParam = env.getProperty("myParam"); //... return true; } } ``` 2. 通过在配置文件定义一个Bean,将配置文件参数值注入到该Bean,然后在HandlerInterceptor通过@Autowired注解注入该Bean即可。 示例代码: 在配置文件定义一个Bean: ```xml <bean id="myConfig" class="com.example.MyConfig"> <property name="myParam" value="${myParam}"/> </bean> ``` 在Interceptor注入该Bean: ```java public class MyInterceptor implements HandlerInterceptor { @Autowired private MyConfig myConfig; //... } ``` 其MyConfig类定义如下: ```java public class MyConfig { private String myParam; public String getMyParam() { return myParam; } public void setMyParam(String myParam) { this.myParam = myParam; } } ``` 这样,就可以在Interceptor通过myConfig.getMyParam()方法获取配置文件参数值了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值