Spring——JavaBean(实现Helloworld类)

如果一个类中只包含属性,setter,getter方法,那么这种类就称为简单的JavaBean。

Spring中配置Bean的主要步骤(实现Helloworld类):

1.新建一个Spring Bean Configuration File文件applicationContext.xml

2.创建一个Helloworld类

public class Helloworld {
	private String name;
	public void setName(String name) {
		this.name=name;
	}
	public void hello() {
		System.out.println("hello:"+name);
	}
	public Helloworld() {
	}
}

类中有一个name属性和相应的写方法,还有一个hello方法用来输出简单的信息。

3.在applicationContext.xml文件中初始化相应的bean

    <bean id="helloWorld" class="com.springtest.Helloworld">
    	<property name="name" value="Spring"></property>
    </bean>

id:唯一。用来标识容器中的bean。

class:bean的全类名,通过反射的方式在IOC容器中创建Bean。所以要求Bean中必须有无参数的构造器。

4.在主方法中调用

ApplicationContext:IOC容器的主要实现接口。

ApplicationContext主要实现类:

  • ClassPsthXmlApplicationContext:从类路径下加载配置文件

新整了refresh()和close()方法,让ApplicationContext具有启动,刷新和关闭上下文的能力。

  • FileSystemXmlApplicationContext:从文件系统中加载配置文件
  • WebApplicationContext
//1.创建Spring的IOC容器对象
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");  //这里创建了对象和赋值
//2.从IOC容器中获取Bean实例
Helloworld h=(Helloworld)ctx.getBean("helloWorld");
h.hello();

这里使用的就是ClassPathXmlApplicationContext类。

在调用getBeen()方法获取对象时,常常有两种调用方法

  1. getBean(String arg0)              通过id获取
  2. getBean(Class<T> arg0)        通过类获取

Helloworld h=ctx.getBean(Helloworld.class);此代码和上面的代码等效。这样调用唯一的好处是不用进行类型的强制转换,但是,如果在容器中对一个类有多个bean对应时,不应该再使用此方法,而应该通过id来获取对象。

5.输出结果

hello:Spring

这里的Sping就是name属性的值,是通过下面代码中的value属性来赋值的,下面代码实际上就是调用Helloworld类的setter方法。

<property name="name" value="Spring"></property>

有关bean更多的知识:https://blog.csdn.net/ljcgit/article/details/81489115

猜你喜欢

转载自blog.csdn.net/ljcgit/article/details/81488669
今日推荐