1. 程式人生 > >通過構造器配置Bean

通過構造器配置Bean

override man bubuko 構造器 image bean rgs lap str

public class Role {
    private Log id;
    private String roleName;
    private String note;
    
    public Role(String roleName, String note) {
        this.roleName = roleName;
        this.note = note;
    }

    @Override
    public String toString() {
        return "Role{" +
                "
id=" + id + ", roleName=‘" + roleName + \‘ + ", note=‘" + note + \‘ + }; } }

xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <bean id="role1" class="com.nf147.manage.spring.Role"> <constructor-arg index="
0" value="總經理"/> <constructor-arg index="1" value="公司管理者"/> </bean> </beans>

  測試代碼:

  public static void main(String[] args) {
        ApplicationContext A=new ClassPathXmlApplicationContext("spring/my-spring.xml");
        Object role1 = A.getBean("role1");
        //System.out.println(((Role)role1).toString());
        System.out.println((Role)role1);

    }

結果:

技術分享圖片

通過構造器配置Bean