版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fangxinde/article/details/78277427
第一步:建立一个类
package com.atguigu.spring.beans;
public class HelloWorld {
private String name;
public void setName(String name){
this.name=name;
}
public void hello(){
System.out.println("hello:"+name);
}
}
第二部配置资源文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!--配置bean
class:bean的全类名通过反射的方式在IOC容器中创建Bean所以要求Bean中必须有无参的构造器
-->
<bean id="h" class="com.atguigu.spring.beans.HelloWorld">
<property name="name" value="Spring----》fangxinde,you are successful"></property>
</bean>
</beans>
第三步:main方法中获取bean
package com.atguigu.spring.beans;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
//ClassPathXmlApplicationContext接口的实现类,该实现类从类路径下来加载配置文件
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
//利用类型返回IOC容器中的Bean,但要求IOC容器中必须智能一个该类型的Bean
HelloWorld helloworld=ctx.getBean(HelloWorld.class);
//HelloWorld helloworld=(HelloWorld) ctx.getBean("helloworld1");
helloworld.hello();
}
}
第四步:运行main方法,得到打印结果
hello:Spring----》fangxinde,you are successful