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

spring入门基础(一)

2015-08-03 17:20 441 查看
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,看看是不是某某某这个人,这个我想是很简单的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: