Spring学习-day01
发表于:2024-11-24 作者:热门IT资讯网编辑
编辑最后更新 2024年11月24日,
package com.atguigu.spring.beans;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * @author 国真 * */public class Main { public static void main(String[] args) { /* //创建一个helloWorld 对象 HelloWorld helloWorld = new HelloWorld(); //设置名字 helloWorld.setUserName("spring"); */ //1. 创建 Spring的IOC容器对象 //ApplicationContext 代表 IOC 容器 //ClassPathXmlApplicationContext:是ApplicationContext接口的实现类,该实现类从类路径下来加载xml配置文件 ApplicationContext ctx = new ClassPathXmlApplicationContext("one.xml"); //2. 从IOC容器中获取Bean实例 //利用 id 定位到 IOC 容器中的 Bean HelloWorld helloWorld = (HelloWorld)ctx.getBean("helloWorld"); Car car = (Car)ctx.getBean("car"); Car car1 = (Car) ctx.getBean("car1"); Person person = (Person) ctx.getBean("person"); Person person2 = (Person) ctx.getBean("person2"); //利用类型返回 IOC 容器中的 Bean, 但要求 IOC 容器中必须只能有一个该类型的 Bean// HelloWorld helloWorld = ctx.getBean(HelloWorld.class); //3. 打印名字 helloWorld.hello(); System.out.println(car); System.out.println(car1); System.out.println(person); System.out.println(person2); }}
package com.atguigu.spring.beans;public class Person { private String name; private int age; private Car car; 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; } public Car getCar() { return car; } public void setCar(Car car) { this.car = car; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", car=" + car + "]"; } public Person(String name, int age, Car car) { super(); this.name = name; this.age = age; this.car = car; } public Person() { super(); }}