Spring(1)管理bean

  1. 关于Struts2的,我以后用一个小项目讲解(flag就立在这里!!!)
  2. 进入正题:先说一下Spring的核心理论:在spring中,所有的对象都会被spring当作核心容器管理的对象,工程为bean,但是,这个bean和以前说到的bean不太一样,这里的bean没有什么要求,只要是对象就行(不用什么私有变量啦,setget方法啦的。)
  3. 现在用IDEA建立一个简单的spring程序
    1. 新建一个项目需要注意的就是项目类型要选择spring  mvc其他的就没啥好说了,图2是IDEA在下载spring需要的jar包,是不是很好用~~
    2. 这是各个文件的位置
    3. 开始打代码,具体的讲解穿插在代码中
      
      package service;
      
      
      /**
       这个没啥好说的,就简单输出
       */
      
       /**
       * Demo Axe
       *
       * @author lin
       * @date 2018/11/25
       */
      
      public class Axe {
           String chop(){
              return "使用斧头砍柴";
          }
      }
      
      package service;
      /**
       * 在这个类中使用Axe,也没啥好说的
       */
      
      /**
       * Demo Person
       *
       * @author lin
       * @date 2018/11/25
       */
      public class Person {
          private Axe axe;
      
          public Axe getAxe() {
              return axe;
          }
      
          public void setAxe(Axe axe) {
              this.axe = axe;
          }
          public void useAxe(){
              System.out.println("我打算去砍点柴火!");
              System.out.println(axe.chop());
          }
      }
      
      package main;
      
      import org.springframework.context.ApplicationContext;
      import org.springframework.context.support.ClassPathXmlApplicationContext;
      import service.Person;
      
      /**
       * 测试类
       */
      
      
      /**
       * Demo BeanTest
       *
       * @author lin
       * @date 2018/11/25
       *
       */
      public class BeanTest {
      
          public static void main(String []args){
              ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
      //       创建spring容器
              
              Person p = applicationContext.getBean("person", Person.class);
      //        在spring中,不用new关键字创建对象,而是由spring创建的
              
              p.useAxe();
          }
      
      
      }
      
      <?xml version="1.0" encoding="GBK"?>
      <!--spring配置文件的根元素-->
      <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns="http://www.springframework.org/schema/beans"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
      	   http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
      
          <!--配置名为person的bean,并指定其实现类-->
          <bean id="person" class="service.Person">
              <property name="axe" ref="axe"/>
              <!--将下面的这个axe当作参数传入Person类的setAxe方法中-->
          </bean>
      
          <!--配置三个bean并且指定其实现类-->
          <bean id="axe" class="service.Axe"/>
          <bean id="win" class="javax.swing.JFrame"/>
          <bean id="date" class="java.util.Date"/>
          
      </beans>
      

猜你喜欢

转载自blog.csdn.net/weixin_39452731/article/details/84475546