zoukankan      html  css  js  c++  java
  • 【Spring】---【IOC入门案例】

    第一步:导入Jar包

    第二步:创建类,在类里面创建方法

     1 public class User {
     2     public void add(){
     3         System.out.println("--------->add");
     4     }
     5     public static void main(String[] args) {
     6         //原始做法
     7         User user = new User();
     8         user.add();
     9     }
    10 }

    第三步:创建Spring配置文件,配置创建类

    • Spring的核心配置文件文件名称和位置不是固定的
    • 建议放在src下,官方建议applicationContext.xml
    • 引入约束(schema)
    1 <beans xmlns="http://www.springframework.org/schema/beans"
    2     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3     xsi:schemaLocation="
    4         http://www.springframework.org/schema/beans 
    5         http://www.springframework.org/schema/beans/spring-beans.xsd">
    6 </beans>
    • 配置对象的创建
    1 <!-- IOC入门 -->
    2 <bean id="user" class="com.tyzr.ioc.User"></bean>

    第四步:写代码测试对象的创建

    注意:这段代码仅仅用来测试(工作中不能用)

    Hibernate一样需要加载文件

    1 @Test
    2     public void testUser(){
    3         //加载核心配置文件,创建对象
    4         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    5         //得到我们配置的对象
    6         //<bean id="user" class="com.tyzr.ioc.User"></bean>
    7         User user = (User)context.getBean("user");
    8         user.add();
    9     }

     

     测试结果

     

    --------->add

    解决配置文件没有提示

     

    配置文件没有提示的问题:

     

    Spring引入的约束是schema,把约束引入到eclipse

     

  • 相关阅读:
    codeforces567E. President and Roads
    codeforces 573C Bear and Drawing
    bzoj4160: [Neerc2009]Exclusive Access 2
    bzoj1251: 序列终结者
    bzoj2534: Uva10829L-gap字符串
    Excel中导入到oracle使用merge into 差异性更新数据库
    文件解压缩公用类
    XML常用操作
    密码加密解密
    GridView中数据行的操作
  • 原文地址:https://www.cnblogs.com/angelye/p/7383806.html
Copyright © 2011-2022 走看看