1.javabean
package com.bean;
public class Hello {
private String hello;
public Hello(String name) {
hello=name;
}
public String getHello() {
return hello;
}
public void setHello(String hello) {
this.hello = hello;
}
public void show() {
System.out.println("hello:"+hello);
}
}
2.配置文件
<?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-4.3.xsd">
<!-- bean就是javabean对象,由spring来创建和管理 ,其实是使用无参构造方法创建对象-->
<!-- singleton表示创建的java对象是单例模式,默认的模式,只存在一个bean,
prototype表示创建的对象是原型模式,即每调用一次getBean就生成一个Bean的实例-->
<!-- 构造函数注入 注意:name指的是构造函数参数的名字 -->
<bean id="Hello" class="com.bean.Hello">
<!-- 根据参数的名字 当构造函数中含有其他bean的对象时,将value换成ref后,值换成类的id-->
<constructor-arg name="name" value="hello"/>
<!-- 根据参数索引 -->
<!-- <constructor-arg index="0" value="hello"/> -->
<!-- 根据类型匹配 -->
<!-- <constructor-arg type="String" value="hello"/> -->
</bean>
</beans>
3.测试类
package com.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.bean.Hello;
public class Test1 {
//控制反转
//控制:指谁来控制对象的创建,spring来创建对象
//反转:程序本身不创建对象,而是变成被动的接受spring创建好的对象
//正转:在程序中主动创建对象
public static void main(String[] arges) {
ApplicationContext context=new ClassPathXmlApplicationContext("config.xml");
Hello hello=(Hello) context.getBean("Hello");
hello.show();
}
}