先贴spring的开发文档,有助于大家学习http://shouce.jb51.net/spring/beans.html#beans-factory-class

一直想研究一下spring bean的控制反转的实现,废话不多说。

1、先建了一个WEB工程,导入相关spring的jar包,装载到tomcat上,成功访问,有不懂的童鞋可以移步http://www.cnblogs.com/qing1002/p/6560332.html。

2.为了方便研究,我将对象的调用直接写在controller里,输出相应的日志,如果可以输出,证明bean是创建成功的,代码如下:

package com.controller;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.entity.User;
import com.entity.World;

@Controller
public class SpringServlet {

    /**
     * @Autowired 自动装载world对象 自动按type装载,也就是bean的class属性
     * 或者@Resource(name="world") 按name装载,也就是bean的id
     */
    @Resource(name="world")    //这里的@Resource(name="world")和@Autowired是一模一样的,
    public World world;

    @RequestMapping("/index")
    public String index(Model model){
        world.worldTest();
        return "index";
    }

    @RequestMapping("/save")
    public String Save(@ModelAttribute("form") User user, Model model) { // user:视图层传给控制层的表单对象;model:控制层返回给视图层的对象
        System.out.println(model.toString());
        model.addAttribute("user", user);
        return "detail";
    }
}

3、然后还写了两个类,代码如下:

package com.entity;

import java.io.Serializable;
import java.util.Date;

import org.springframework.stereotype.Repository;

@Repository
public class User implements Serializable{

     private static final long serialVersionUID = 1L;
        private Integer id; // id
        private String name; // name
        private String pwd; // pwd
        private Integer age; // age
//        private Date creatTime; // creatTime

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getPwd() {
            return pwd;
        }

        public void setPwd(String pwd) {
            this.pwd = pwd;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

//        public Date getCreatTime() {
//            return creatTime;
//        }
//
//        public void setCreatTime(Date creatTime) {
//            this.creatTime = creatTime;
//        }
        public String toString(){
            return name+"333"+age;
        }
        public void test(){
            System.out.println("22222");
        }
}
package com.entity;

import java.io.Serializable;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;

public class World implements Serializable{

    private static final long serialVersionUID = 1L;

//  @Resource(name="user")   //这里的@Resource(name="user")和@Autowired是一模一样的,
    private User user;

    private String type;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public void worldTest(){
        user.test();
        System.out.println("worldTest------" + type+"------"+user.getName());
    }
}

在上述代码中,SpringServlet里的world是IOC容器通过标签@Resource从配置文件中根据name装载的,而World类里同样有一个User类,这个类没有加标签,他是通过setUser()的方法装载的user bean类,配置文件里配置一下bean类,代码如下:

<bean id="world" class="com.entity.World">
        <property name="user" ref="user" />
        <property name="type" value="stringWorld"></property>
    </bean>
    <bean id="user" class="com.entity.User"/>

这样,SpringServlet里的world就通过控制反转的方式生成对象,然后调用world的worldTest()方法,就可以成功输出,如果world对象没有成功生成,调用他的方法的时候会报 java.lang.NullPointerException,

后台日志打印:

证明对象已经成功创建,如果想给对象添加属性,可以直接在配置文件里添加,如下形式:

<bean id="user" class="com.entity.User">
        <property name="id" value="1"></property>
        <property name="name" value="guan"></property>
        <property name="pwd" value="111111"></property>
        <property name="age" value="12"></property>
    </bean>

最后,我想让代码更精简,不想写那么多配置文件,可以采用注解的形式,为World.java的User属性添加@Autowired或者@Resource(name="user")标签,然后改一下配置文件,只需要写两行,如下:

<bean id="world" class="com.entity.World" />
<bean id="user" class="com.entity.User"/>

是不是代码精简了好多,也装逼了好多,程序可以成功运行,同时日志台输出:

然后就结束了,很多东西还有待学习,,,有很多不明白,最后贴一下配置文件springSerblet-config.xml代码:

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

    <!-- 使用默认的注解映射 -->
    <mvc:annotation-driven />
    <!-- <mvc:resources location="/" mapping="/index.html" />
      <context:annotation-config></context:annotation-config>-->
    <!-- world bean类 -->
    <bean id="world" class="com.entity.World" />
        <!-- <property name="user" ref="user" />
        <property name="type" value="stringWorld"></property>
    </bean> -->
    <bean id="user" class="com.entity.User"/>
    <!-- user bean类 -->
    <!-- <bean id="user" class="com.entity.User">
        <property name="id" value="1"></property>
        <property name="name" value="guan"></property>
        <property name="pwd" value="111111"></property>
        <property name="age" value="12"></property>
    </bean> -->
    <!-- <bean id="world" class="com.entity.World">
        <property name="user">
            <idref bean="user"/>
        </property>
        <property name="type" value="stringWorld"></property>
    </bean> -->
    <!-- 自动扫描controller包中的控制器 -->
    <context:component-scan base-package="com.controller" />
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="/index.do">controllerDoem</prop>
            </props>
        </property>
    </bean>

     <bean id="controllerDoem" class="com.controller">
        <property name="view">
            <value>index</value>
        </property>
    </bean>-->

</beans>

applicationContext.xml和web.xml里的是一些web工程基本配置,不要动它,整体结构是这样的:

最后,欢迎各位大神指导,指出错误和不足。。。。   正在努力学习中。。。

spring Bean类自动装载实现的更多相关文章

  1. spring bean autowire自动装配

    转自:http://blog.csdn.net/xiao_jun_0820/article/details/7233139 autowire="byName"会自动装配属性与Bea ...

  2. php类自动装载、链式操作、魔术方法

    1.自动装载实例 目录下有3个文件:index.php load.php tests文件夹 tests文件夹里有 test1.php <?php namespace Tests; class T ...

  3. jdbc操作根据bean类自动组装sql,天啦,我感觉我实现了hibernate

    场景:需要将从ODPS数仓中计算得到的大额可疑交易信息导入到业务系统的mysql中供业务系统审核.最简单的方式是用阿里云的组件自动进行数据同步了.但是本系统是开放是为了产品化,要保证不同环境的可移植性 ...

  4. Spring bean的自动装配属性

    bean的自动装配属性能简化xml文件配置. bean 的自动装配属性分为四种: 1.byName 2.byTyoe 3.constructor 4. autodetect byName: 它查找配置 ...

  5. Spring框架——IOC 自动装载

    IOC自动装载有两种形式 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns=" ...

  6. Spring核心技术(八)——Spring自动装载的注解

    本文针对自动装载的一些注解进行描述. 基于注解的容器配置 @Required注解 @Required注解需要应用到Bean的属性的setter方法上面,如下面的例子: public class Sim ...

  7. 解决Spring+Quartz无法自动注入bean问题

    问题 我们有时需要执行一些定时任务(如数据批处理),比较常用的技术框架有Spring + Quartz中.无奈此方式有个问题:Spring Bean无法自动注入. 环境:Spring3.2.2 + Q ...

  8. 8 -- 深入使用Spring -- 2...1 搜索Bean类

    8.2.1 搜索Bean类 既然不再使用Spring配置文件来配置任何Bean实例,那么只能希望Spring会自动搜索某些路径下的Java类,并将这些Java类注册成Bean实例. tips:Rail ...

  9. 【转】Spring Bean属性解析

    转载自:http://wenku.baidu.com/view/30c7672cb4daa58da0114ae2.html Bean所以属性一览: <bean id="beanId&q ...

随机推荐

  1. laravel中token的使用方式

    在form表单里提交表单时,可 <form action="" method="post"> <?php  echo csrf_field() ...

  2. Java 基础 break和continue关键字的使用

    break&continue关键字的使用 break:使用在switch...case语句或者循环结构语句中,表示结束当前循环. 示例代码: public class TestBreak { ...

  3. Linux常用操作命令(三)

    查看linux日志某几行 用逆序显示命令tail查看 命令格式:tail [  -r ] [  -n Number ] [ File ] [一]从第3000行开始,显示1000行.即显示3000~39 ...

  4. Array和ArrayList的区别与联系

    博主今天去了一个java的实习面试,发现有好多java最基础的数据结构对于博主来说反而感到陌生,在面试官问一些常见的例如HashMap这样的数据结构,博主能回答的头头是道,但是在问到Array和Arr ...

  5. 【LeetCode】119. Pascal's Triangle II

    题目: Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3,Return [ ...

  6. JAVA基础——Arrays工具类十大常用方法

    Arrays工具类十大常用方法 原文链接:http://blog.csdn.net/renfufei/article/details/16829457 0. 声明数组 String[] aArray ...

  7. winform .net2.0的程序如何运行于.net 4.x

    约束 最近有一个winform项目,要求: (1)程序能够运行在winxp, win7, win8, win10中 (2)安装尽可能简单,尽量不要安装.net framework.即使要安装也要尽可以 ...

  8. win10下安装python

    1. 在官网下载python:https://www.python.org/ftp/python/3.5.2/python-3.5.2-amd64.exe 这里下载的是3.5.2版. 2. 双击exe ...

  9. CentOS7下使用YUM安装mariadb10

    1:由于centos7 默认使用yum安装MySQL的话就会安装mariadb,只是安装的版本停留在mariadb5.x,版本比较低.如果我们需要安装mariadb10这里就需要删除mariadb-l ...

  10. Java+Tomcat + Idea + Jrebel 实现热部署

    1. 首先安装idea的jrebel插件, jrebel是收费的,所以要在网上下载验证码. 2. 安装好以后再setting 菜单能看到一个jrebel的菜单. 3.  4.其中需要选中frame失去 ...