spring的入门之helloworld

来源:互联网 发布:张海山锐线体简mac 编辑:程序博客网 时间:2024/06/05 23:51
定义一个Helloworld类

类中有一个属性name

String name;

有一方法给属性name赋值、

public void setName(String name){

this.name=name;

}

方法hello()输出结果

hello(){system.out.print("hello"+name)}


没使用spring框架之前:
创建对象
 
Helloworld helloworld=new Helloword();

赋值


helloworld.setName("spring");

调用方法

helloworld.hello();
使用spring:

新建spring配置文件 spring Bean configuration file(.xml)
配置
<bean id="helloworld"class="类名路径" > //通过类名用反射的方式创建对象
<property name="name" value="spring"></property>//name为对象的属性名
</bean>
在实现类中:
1、创建spring的IOC容器对象
ApplicationContext ctx=new ClassPathxmlApplicationContext("spring配置文件名")//ApplicationContext 代表就是IOC容器  这是一个接口//ClassPathxmlApplicationContext表示配置文件在类路径下

2、从IOC容器中获取Bean实例
Helloworld helloworld=ctx.getBean("helloworld");//这里的helloworld是在配置<bean>时的id

3、调用方法
helloworld.hello();

说明在创建spring的IOC的容器时 会调用构造器对配置文件中的bean进行初始化,同时调用set方法进行赋值
原创粉丝点击