Spring Bean管理

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值