zoukankan      html  css  js  c++  java
  • Java框架之Spring(二)

    前一篇博客讲述了Spring的一些基础概念,下面我们来创建第一个Spring程序吧。

    步骤如下:

    1) 导包

    2) 配置文件

    附没有提示的情况 

    MyEclipse ->File and Editors -XML ->XML Catlog, 点击 add,找到上面的文件 spring-beans-3.1.xsd,然后 Key type 选 SchemaLoaction, key 后面加上 spring-beans-3.1.xsd即可。

    //beans.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"
          xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
                
          //这里自己根据需要去设置,将UserInf这个类交给Spring管理 
          <bean name="userInfo_name" class="cat.beans.UserInfo" >
          <property name="id" value="1" />
          <property name="userName" value="赵明明" />
          <property name="password" value="123" />
          <property name="note" value="这是备注" />
          </bean>
                
    </beans>
    public class Test {
        public static void main(String[] args) {
        //初始化容器
        ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
                        
        UserInfo user=(UserInfo) ctx.getBean("userInfo_name");//下面讲解两种等效方法
                        
        /*可以这样,条件是在beans.xml中只有一个userInfo_name的情况下。
        *多了,就不能用这个了,因此推出可以用下面带参数的方法
        *UserInfo user=ctx.getBean(UserInfo.class);
        */
                        
        //带参数的方法
        //UserInfo user=ctx.getBean("userInfo_name", UserInfo.class);
                        
        System.out.println(user);
                        
        /*附加:初始化容器,也可以这样写
        *ApplicationContext ctx= new ClassPathXmlApplicationContext("beans.xml");
        *因为 ApplicationContext 是 ClassPathXmlApplicationContext的父类
        */
                }
    
    }
  • 相关阅读:
    下一座“金矿”:移动医疗的契机和风险
    android ViewStub简单介绍
    IT人员必须掌握的10项软技能
    Android ListView item 点击事件失效问题的解决
    前端之Android入门(3):MVC模式(上)
    Android 错误提示: Can't create handler inside thread that has not called Looper.prepare()
    Android 性能优化提示
    Android 学习资源
    元素水平对齐
    div垂直居中
  • 原文地址:https://www.cnblogs.com/1693977889zz/p/8137515.html
Copyright © 2011-2022 走看看