javaweb(spring)中三种实例化bea方法之构造函法

1:在项目的pom.xml中加入spring框架的相关jar
<dependencies></dependencies>加入如下代码:

  <dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-jdbc</artifactId>
		<version>4.2.4.RELEASE</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-tx</artifactId>
		<version>4.2.4.RELEASE</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-context</artifactId>
		<version>4.2.4.RELEASE</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-core</artifactId>
		<version>4.2.4.RELEASE</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-context-support</artifactId>
		<version>4.2.4.RELEASE</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
		<version>4.2.4.RELEASE</version>
 </dependency> 

2:实例化和初始化ApplicationContext,我们通过ContextLoaderListener来 实现,找到项目工程中的web.xml文件加入如下 的代码:

<!--初始化和实例化ApplicationContext -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring-mvc.xml</param-value>
	</context-param>
	<listener>
		<description>spring监听器</description>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener> 

3:创建类

package com.gouzao;

public class Student {
	private Teacher teacher;

	public Teacher getTeacher() {
		return teacher;
	}

	public void setTeacher(Teacher teacher) {
		this.teacher = teacher;
	}

	public void say() {
		this.teacher.say();
		System.out.println("Student say!");
	}

}

package com.gouzao;

public class Teacher {

	public void say() {
		// TODO 自动生成的方法存根
		System.out.println("Teacher say!");

	}

}

4:在spring.xml 中配置bean,程序会根据spring.xml来初始化和实例化bean

 <bean id="teacher" class="com.gouzao.Teacher"/>
    <bean id="student" class="com.gouzao.Student">    
    	<property  name="teacher" ref="teacher"></property>
    </bean>

5:添加测试类:

package com.gouzao;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Demo {
	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
		//ApplicationContext  通过ClassPath找到了xml文件,实例化装载完成了ApplicationContext。这里 的第二步配置可以省略!
		Student student = (Student) applicationContext.getBean("student");
		student.say();

	}
}

运行结果为
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值