Using spring's special bean s to complete the distributed configuration

Keywords: Java Spring xml encoding

I. foreword

Decentralized configuration idea: create a properties file, add data, configure the properties file in the beans file first, and then use placeholders to reference data in beans

  1. For many processing interfaces in the bean's life cycle, the processing method is spring's own bean, that is, spring's special bean

2. When the property file is imported through context: Property placeholder, there are multiple required, number interval

The 3.beans file uses placeholders to reference the contents of the properties file: eg.${key}


II. Decentralized configuration

Through the self built properties file, configure the key value, read it in the spring configuration file, and realize the decentralized configuration file



Configuration file beans:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns=""
    <!-- Introducing our file -->
    <!-- One way:To configure bean 
    <bean class="PropertyPlaceholderConfigurer">
        <property name="locations">
<!-- Mode two: -->
    <context:property-placeholder location="classpath:com/ahd/dispatcher/"></context:property-placeholder>
    <bean id="dbutil" class="com.ahd.dispatcher.DBUtil">
        <property name="username"><value>${username}</value></property>
        <property name="password"><value>${password}</value></property>
        <property name="drivername"><value>${driver}</value></property>



DBUtil class:

package com.ahd.dispatcher;

public class DBUtil {
    private String username;
    private String password;
    private String drivername;
    public DBUtil() {
    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 String getDrivername() {
        return drivername;
    public void setDrivername(String drivername) {
        this.drivername = drivername;


Test class:

package com.ahd.dispatcher;

import org.springframework.context.ApplicationContext;

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ApplicationContext ac=new ClassPathXmlApplicationContext("com/ahd/dispatcher/beans.xml");
        DBUtil dbutil = (DBUtil) ac.getBean("dbutil");
        System.out.println(dbutil.getUsername()+"    "+dbutil.getPassword());


Posted by amites on Wed, 04 Dec 2019 01:29:06 -0800