1. Bean实例化的方式
- 第一种 无参数构造创建
- `<?xml version="1.0" encoding="UTF-8"?>
`
-
`public class Hello {
private String name = “helloworld”;public Hello() {
System.out.println(“Hello 无参构造”);
}public Hello(String name) {
this.name = name;
}public String getName() {
return name;
}public void setName(String name) {
this.name = name;
}
public void hello() {
System.out.print(“hello:” + name);
}
}`
public class HelloPrinter {
private Hello hello;
public HelloPrinter() {
System.out.println("HelloPrinter 无参构造");
}
public HelloPrinter(Hello hello) {
this.hello = hello;
}
public Hello getHello() {
return hello;
}
@Autowired //自动注入对象
public void setHello(Hello hello) {
this.hello = hello;
}
public void printMessage(){
System.out.println(this.hello.getName());
}
}
@ComponentScan
public class Main {
public static void main(String[] args) {
/* System.out.println(“applicationSpring”);
ApplicationContext context = new AnnotationConfigApplicationContext(Main.class);
//从容器中获取Hello对象
Hello hello = context.getBean(Hello.class);
HelloPrinter helloPrinter = context.getBean(HelloPrinter.class);
// helloPrinter.setHello(hello);
helloPrinter.printMessage();*/
//XML方式
//1 初始化Spring容器
ApplicationContext context = new ClassPathXmlApplicationContext("MATE_INF/applicationContext.xml");
//从容器中获取HelloPrinter对象
HelloPrinter helloPrinter = context.getBean(HelloPrinter.class);
helloPrinter.printMessage();
}
}
-
第二种使用静态工厂
-
通过XML中 bean属性的getBean 也就是写在BeanFactory中getBean()返回对象
`public class BeanFactory {//静态方法 返回对象
public static Hello getBean(){
return new Hello();
}
}
` -
- 第三种使用实例工厂
- 先创建工厂对象,再调用工厂对象的方法创建Hello对象
<!--创建工厂对象-->
<bean id="bean3Factory" class="com.gfr.controller.Bean2Factory"></bean>
<bean id="bean2" factory-bean="bean3Factory" factory-method="getBean"></bean>
public class Bean2Factory {
// 返回对象
public Hello getBean(){
return new Hello();
}
}