一、装配一个bean
二、依赖注入的几种方式
com.cy.entity People.java:
package com.cy.entity;public class People { private int id; private String name; private int age; public People() { super(); // TODO Auto-generated constructor stub } public People(int id, String name, int age) { super(); this.id = id; this.name = name; this.age = age; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "People [id=" + id + ", name=" + name + ", age=" + age + "]"; } }
spring管理bean的xml: beans.xml:
com.cy.factory下的
静态工厂:PeopleFactory2.java:
package com.cy.factory;import com.cy.entity.People;public class PeopleFactory2 { public static People createPeople(){ People people = new People(); people.setId(6); people.setName("小八"); people.setAge(88); return people; }}
非静态工厂:PeopleFactory.java:
package com.cy.factory;import com.cy.entity.People;public class PeopleFactory { public People createPeople(){ People people = new People(); people.setId(5); people.setName("小七"); people.setAge(77); return people; }}
测试代码:
package com.cy.service;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.cy.entity.People;public class Test { @SuppressWarnings("resource") public static void main(String[] args) { ApplicationContext ac =new ClassPathXmlApplicationContext("beans.xml"); People people = (People) ac.getBean("people"); System.out.println(people); //属性注入 People people2 = (People) ac.getBean("people2"); System.out.println(people2); //构造函数注入 通过类型 People people3 = (People) ac.getBean("people3"); System.out.println(people3); //工厂方法注入 非静态工厂 People people6 = (People) ac.getBean("people6"); System.out.println(people6); //工厂方法注入 静态工厂 People people7 = (People) ac.getBean("people7"); System.out.println(people7); }}
console打印: