您的位置:首页 > 编程语言 > Java开发

(一)spring的bean简单的配置

2017-10-18 20:32 239 查看
第一步:建立一个类

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: