spring基于注解的方式获取.properties文件中的数据

来源:互联网 发布:dnf决战人工智能62 编辑:程序博客网 时间:2024/06/01 09:03

 最近开始学习spring的相关知识,因为很久没有写过了,所以从现在开始,我要把我的学习中遇到的难点和容易发生的bug记录下来。

昨天晚上在看关于.properties的使用的相关内容,遇到了一些bug,一直解决不了,由于今天要交作业,所以我不得不放下手头的事情赶作业。今天下午上完课重新打开电脑在看昨天的内容,才发现还是由于粗心大意,写错了一处的配置,这个错误真行让我“心醉神迷”呀!

行了,废话不多说,直接上我的代码,也给有需要的朋友一点帮助。


jdbc.properties

<span style="font-size:14px;">driverClassName=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/sampledbuserName=rootpassword=1234</span>


bean2.xml

<span style="font-size:14px;"><?xml version="1.0" encoding="UTF-8" ?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd"><context:component-scan base-package="Demon02"/>              <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">       <property name="locations">        <list>       <value>classpath:Demon02/jdbc.properties</value>       <!-- <value>classpath*:Demon02/jdbc.properties</value> -->       </list>       </property>       </bean>       <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">       <property name="properties" ref="configProperties"></property>       </bean>                     </beans></span>

在这个文件中的<context:component-scan base-package="Demon02"/>了,我竟然吧扫描的路径直接写成这个包下面的bean类了,昨晚找bug是怎么找都发现写的代码是没有问题的,直到今天下午从头有看了一遍代码,才发现问题,实在是惭愧。


beansClass.java

<span style="font-size:14px;">package Demon02;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;@Componentpublic class beansClass {@Value("#{configProperties['driverClassName']}")private String driverClassName;@Value("#{configProperties['url']}")private String url;public String getDriverClassName(){return driverClassName;}public String getUrl(){return url;}}</span>


MainClass.java


<span style="font-size:14px;">package Demon02;import javax.annotation.Resource;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/* * 利用注解的方式读取properties文件中的数据*/public class MainClass {@Testpublic static void main(String args[]){ApplicationContext ctx = new ClassPathXmlApplicationContext("Demon02/bean2.xml");beansClass b2;b2 = (beansClass)ctx.getBean(beansClass.class);System.out.println(b2.getDriverClassName());System.out.println(b2.getUrl());//System.out.println();}}</span>

这次的bug很小,可是导致的后果却是很严重,浪费了如此多宝贵的时间,故写下来,以此来警醒我自己,一定要细心细心在细心!!!


1 0