spring中管理bean的方式,以及初始化参数的2种方式

注:constructor-arg:通过构造函数注入。 
       property:通过setter对应的方法注入。

1、定义一个Class

public class ExceptionMonitor {

  private String LOG_FILE_PATH;// 日志文件路径
  private String PROJECT_NAME;// 项目名称

  public String getLOG_FILE_PATH() {
    return LOG_FILE_PATH;
  }

  public void setLOG_FILE_PATH(String lOG_FILE_PATH) {
    LOG_FILE_PATH = lOG_FILE_PATH;
  }

  public String getPROJECT_NAME() {
    return PROJECT_NAME;
  }

  public void setPROJECT_NAME(String pROJECT_NAME) {
    PROJECT_NAME = pROJECT_NAME;
  }

}

2、在applicationContext.xml中定义一个bean

<bean class="com.search.Jobs.ExceptionMonitor">
  <property name="LOG_FILE_PATH" value="/opt/apache-tomcat-search-bridge/logs/catalina.out" />
  <property name="PROJECT_NAME" value="search_bridge" />
</bean>

3、定义一个类

package com.search;

import java.util.List;
import java.util.Map;

public class Person {
  private int age;
  private String name;
  private List<String> interestList;
  private Map<String, Integer> friendMap;
  private boolean isMarried;

  public Person(int age, String name, List<String> interestList, Map<String, Integer> friendMap, boolean isMarried) {
    this.age = age;
    this.name = name;
    this.interestList = interestList;
    this.friendMap = friendMap;
  this.isMarried = isMarried;
  }

  public Person() {}

}

<bean id="student" class="com.search.Person">
  <constructor-arg name="age" value="26" />
  <constructor-arg name="name" value="student" />
  <constructor-arg name="interestList">
  <list>
    <value>run</value>
    <value>travel</value>
    <value>photography</value>
  </list>
  </constructor-arg>
  <constructor-arg name="friendMap">
    <map>
      <entry key="tom" value="24" />
      <entry key="wilson" value="25" />
    </map>
  </constructor-arg>
  <constructor-arg name="isMarried" value="false" />
</bean>

程序加载次类时熟悉的值就会被初始化/注入

posted on 2019-08-02 11:13  牛鼻子老赵  阅读(2600)  评论(0编辑  收藏  举报