spring入门基础(一)

spring是ssh框架之一,总结来说它是一个容器框架,用于配置bean并维护bean之间的关系。说几个概念,第一个就是bean,bean是java中的任何一种对象 javabean/service/action/数据源./dao,然后是ioc(控制反转 inverse of control) 接着是di( dependency injection 依赖注入)

我们都知道Struts框架无论是2还是1都是作用在web层上的框架,通过配置Struts.cfg.xml文件来实现JSP和action之间的联系;hibernate是orm框架,用于持久层的框架;spring是将这些整体串联起来的一个框架,相当于是一跟线横跨这几块内容,可以通过一个小demo快速建一个spring项目,来快速明白spring是干什么的


首先先建一个JavaProject即可(spring不一定只能用于web项目),跟Struts和hibernate一样,使用spring同样需要引入jar包,这个在网上直接搜,很容易下载到,直接引进去就可以了。

然后手动创建一个核心配置文件applicationContext.xml(名字可以任意起,后边自己配置路径的时候记住就好), [hibernate有核心 hibernate.cfg.xml struts核心文件 struts-config.xml], 该文件一般放在src目录下,该文件中引入 xsd文件 ,和hibernate的配置文件(dtd文件还是有所不同的),开头部分可以直接进行复制:

<?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:context="http://www.springframework.org/schema/context"
		xmlns:tx="http://www.springframework.org/schema/tx"
		xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
				http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
				http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

</beans>

然后我们开始配置:

这个是Java的一个类:

package com.service;

public class UserService {
	private String username;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}
	public void sayHello(){
		System.out.println("Hello, " + username);
	}
}

对应的配置我们的bean:

<?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:context="http://www.springframework.org/schema/context"
		xmlns:tx="http://www.springframework.org/schema/tx"
		xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
				http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
				http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

<bean id="userService" class="com.service.UserService">
<!-- 提现一个注入的概念,这个username就是类里自己的属性 -->
	<property name="username">
		<value><span style="font-family:Microsoft YaHei;">某某某</span></value>
	</property>
</bean>
</beans>

这个案例中,没有new一个对象来获得username,而是通过spring的配置,注入了username的值,测试的时候我们可以直接输出这个username,看看是不是某某某这个人,这个我想是很简单的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值