Spring基础之搭建简单的项目

来源:互联网 发布:json如何使用 编辑:程序博客网 时间:2024/05/16 06:00

       spring 是无侵入性的轻量级容器框架,用于配置bean,并维护bean之间关系.

       spring 的Ioc/DI(控制反转/依赖注入)
        Ioc(控制反转,以前是应用程序去创建并管理对象,现在将这个任务交给Spring容器,就好像以前的军区既要建立训练军队,战时又要指挥军队打仗,现在是军区(Spring)主建,战区(应用程序)主战)。Ioc是从宏观上讲控制的反转,而DI是指具体如何实现Ioc,就是使用依赖注入,来配置及管理对象的依赖关系。

       spring 的AOP(面向切面编程)
       是OOP的补充和延续,把程序分解为方面或关注点。

       创建一个简单的Spring项目

  1. 引入spring的开发包(最小配置spring.jar 该包把常用的jar都包括, 还要 写日志包 common-logging.jar)
    这里写图片描述
  2. 创建spring的一个核心文件 applicationContext.xml, [hibernate有核心 hibernate.cfg.xml struts核心文件 struts-config.xml], 该文件一般放在src目录下。
    这里写图片描述
  3. 编写javabean
//用户public class UserService {private String name;private CatService catservice;public String getName() {    return name;}public void setName(String name) {    this.name = name;}public CatService getCatservice() {    return catservice;}public void setCatservice(CatService catservice) {    this.catservice = catservice;}public void sayHello(){    System.out.println("hello "+name);    catservice.sayMiao();}}//猫public class CatService {private String name;public String getName() {    return name;}public void setName(String name) {    this.name = name;}public void sayMiao(){    System.out.println("miaomiao "+name);}}

4.配置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:p="http://www.springframework.org/schema/p"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"><!-- 在容器文件中配置bean(dao/service/action/数据源/domain) -->    <!-- bean元素的作用是,当我们的spring框架加载时,会自动创建一个bean,并放入内存管理起来    相当于UserService userservice = new UserService();    userservice.setName("wmj");    这里体现了注入的概念     -->    <bean id="userService" class="com.service.UserService">    <property name="name">    <value>wmj</value>    </property>    <property name="catservice" ref="catservice"/>    </bean>    <bean id="catservice" class="com.service.CatService">    <property name="name" value="丢爷"/>    </bean> </beans>

5.调用

public class Test {public static void main(String[] args) {    //得到spring的applicationContext对象    ApplicationContext ac = new ClassPathXmlApplicationContext("ApplicationContext.xml");    UserService us = (UserService) ac.getBean("userService");    us.sayHello();}}

6.运行结果

hello wmjmiaomiao 丢爷
原创粉丝点击