通过构造器配置Bean

 

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);

    }

 

 结果:

 

posted @ 2018-12-14 23:19  随★风  阅读(442)  评论(0编辑  收藏  举报