<!-- 配置bean class: bean的全类名,通过反射的方式在 IOC 的容器中创建 Bean. 所以要求 中必须有无参数的构造器 id:标识容器中的 bean. id 是唯一的 --> <!-- 使用 setter 方法进行属性注入 --> <bean id="helloWorld" class="com.atguigu.spring.beans.HelloWorld"> <property name="userName" value="Spring"></property> </bean> <!-- 使用构造器注入属性值可以指定参数的位置和参数的类型,以区分重载的构造器 --> <bean id="car" class="com.atguigu.spring.beans.Car"> <constructor-arg value="1000" index="0"></constructor-arg> <constructor-arg value="Audi" index="1"></constructor-arg> <constructor-arg value="shanghai" type="java.lang.String"></constructor-arg> </bean>
Package Com.atguigu.spring.beans;import Org.springframework.context.applicationcontext;import org.springframework.context.support.classpathxmlapplicationcontext;/** * @author Country True * */public class Main {public stat IC void Main (string[] args) {/*//Create a HelloWorld object HelloWorld HelloWorld = new HelloWorld (); Set the name Helloworld.setusername ("Spring"); *///1. Create a Spring IOC container object//applicationcontext represents the IOC container//classpathxmlapplicationcontext: is the implementation class of the ApplicationContext interface, The implementation class loads the XML configuration file from the classpath applicationcontext ctx = new Classpathxmlapplicationcontext ("One.xml"); 2. Gets the bean instance from the IOC container//uses the ID to locate the bean in the IOC container 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"); Returns the Bean in the IOC container using the type, but requires the IOC capacityThere must be only one bean//HelloWorld HelloWorld = Ctx.getbean (helloworld.class) of that type in the device; 3. Print name 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(); }}
Spring Learning-day01