applicationContext.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">

<!--
配置bean
class: bean 全类名,通过反射的方式在IOC 容器中创建Bean。所以要求Bean 中必须有无参数的构造器
id: 标识容器中的bean. id 唯一
-->
<bean ></constructor-arg>
</bean>

</beans>

Car.java

package com.hy.spring.beans;

public class Car {
private String company;
private String brand;
private double price;
private int maxSpeed;

public Car(String company, String brand, double price) {
super();
this.company = company;
this.brand = brand;
this.price = price;
}

public Car(String company, String brand, int maxSpeed) {
super();
this.company = company;
this.brand = brand;
this.maxSpeed = maxSpeed;
}

@Override
public String toString() {
return "Car [company=" + company + ", brand=" + brand + ", maxSpeed="
+ maxSpeed + ", price=" + price + "]";
}
}


HelloWord.java

package com.hy.spring.beans;

public class HelloWord {
private String name;

public void setName(String name) {
System.out.println("setName:" + name);
this.name = name;
}

public void hello(){
System.out.println("Hello:" + name);
}

public HelloWord() {
System.out.println("HelloWorld's Constructor");
}
}


Main.java

 

package com.hy.spring.beans;

 

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

 

public class Main {

 

public static void main(String[] args) {
//1.创建 Spring 的 IOC容器的对象
// ApplicationContext 代表IOC容器
// ClassPathXmlApplicationContext : 是 ApplicationContext接口的实现类。从类路径下加载配置文件
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//2.从IOC容器中获取Bean实例
//利用ID 定位到IOC 容器中的bean
HelloWord helloWord = (HelloWord) ctx.getBean("helloWord");
//利用类型返回IOC 容器中的bean,但要求IOC容器中必须只能有一个该类型的bean
//HelloWord helloWord = (HelloWord) ctx.getBean(HelloWord.class);
//3.调用hello方法
helloWord.hello();

Car car = (Car) ctx.getBean("car");
System.out.println(car);
car = (Car) ctx.getBean("car1");
System.out.println(car);

}

 

}

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-07-06
  • 2021-08-14
  • 2022-12-23
  • 2018-07-27
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-01-07
  • 2021-10-09
  • 2021-07-10
  • 2021-10-30
  • 2022-12-23
  • 2022-03-02
相关资源
相似解决方案