关于资源文件中的字段是如何注入到spring bean中的

我们为了不硬编码,把一些配置型的数据或者常量配置到properties文件中:

eg:

jdbc.meeting.url = 192.168.1.6:1521:test
jdbc.meeting.username =system
jdbc.meeting.password =oracle
hibernate.show_sql=false

ftp.ipAdrress=192.168.1.33
ftp.port=21
ftp.username=guo
ftp.password=111111

ftp.localPathRoot=D://ftpLocalFiles//
ftp.remotePathRoot=/generatorFiles/

然后我们直接在代码中调用bean的一个常量获取这个值。

private String ftpIpAddress;
	private int ftpPort;
	private String ftpUserName;
	private String ftpPassword;
	
	//FTP路径配置
	private String ftpLocalPathRoot;
	private String ftpRemotePathRoot;
	
	public String getFtpLocalPathRoot() {
		return ftpLocalPathRoot;
	}

	public void setFtpLocalPathRoot(String ftpLocalPathRoot) {
		this.ftpLocalPathRoot = ftpLocalPathRoot;
	}

	public String getFtpRemotePathRoot() {
		return ftpRemotePathRoot;
	}

	public void setFtpRemotePathRoot(String ftpRemotePathRoot) {
		this.ftpRemotePathRoot = ftpRemotePathRoot;
	}

	public void setFtpIpAddress(String ftpIpAddress) {
		this.ftpIpAddress = ftpIpAddress;
	}

	public void setFtpPort(int ftpPort) {
		this.ftpPort = ftpPort;
	}

	public void setFtpUserName(String ftpUserName) {
		this.ftpUserName = ftpUserName;
	}

	public void setFtpPassword(String ftpPassword) {
		this.ftpPassword = ftpPassword;
	}
	
	public String getFtpIpAddress() {
		return ftpIpAddress;
	}

	public int getFtpPort() {
		return ftpPort;
	}

	public String getFtpUserName() {
		return ftpUserName;
	}

	public String getFtpPassword() {
		return ftpPassword;
	}
}

即可获取对应的值。做法:

配置corePropertyConfigurer

    <bean id="corePropertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:sys-config.properties</value>
			</list>
		</property>
	</bean>

配置service或bean的时候 进行注入:

 <bean id="ftpService"
	    class="com.wirelesscity.tools.ftp.FtpServiceImpl">
	    <property name="ftpIpAddress">
			<value>${ftp.ipAdrress}</value>
		</property>
		<property name="ftpPort">
			<value>${ftp.port}</value>
		</property>
		<property name="ftpUserName">
			<value>${ftp.username}</value>
		</property>
		<property name="ftpPassword">
			<value>${ftp.password}</value>
		</property>
		<property name="ftpLocalPathRoot">
			<value>${ftp.localPathRoot}</value>
		</property>
		<property name="ftpRemotePathRoot">
			<value>${ftp.remotePathRoot}</value>
		</property>
	</bean>



你可能感兴趣的:(spring)