Spring入门简例

来源:互联网 发布:网络语言打麻将 编辑:程序博客网 时间:2024/06/05 11:01

1.控制反转IOC/依赖注入DI

控制反转:当我们调用一个类或者方法的时,不再由我们去创建这个类的对象,而是将控制权给Spring。

依赖注入:Spring主动创建被调用对象,然后将这个对象注入到我们的类中,使得我们可以使用它。

2.AOP切面编程

将方法看做一个切面,在这个切面前后,我们可以设置一定的方法,进行一些特殊的处理。

3.编码过程

(1)需要一个bean,设定注入方法。

      注入方法:a.设置注入,需要有setter函数;

                       b.构造注入,需要有构造函数。

(2)bean.xml,设置bean和类的关系,并关联默认的注入值。

(3)获取bean.xml,创建实例,直接调用方法。

4.入门实例

(1)需要的jar包和工程结构

jar包下载地址:http://pan.baidu.com/s/1sjDbzrR 



(2)bean.xml配置文件,在src目录下

<?xml version="1.0" encoding="UTF-8"?><beansxmlns: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-3.0.xsd">    <bean id="person" class="com.test.bean.Person">         <property name="name" value="baymax"/>         <property name="age" value="10"/>     </bean> </beans>

(3)Person类,使用setter注入方法

package com.test.bean;publicclass Person {   private String name;   privateint age;   public String getName() {       return name;   }   publicvoidsetName(String name) {       this.name = name;   }   publicint getAge() {       return age;   }   publicvoid setAge(int age) {       this.age = age;   }   publicvoid info(){       System.out.println("睡你麻痹起来嗨!!");       System.out.println("name:"+getName()+"age:"+getAge());   }}

(4)text类

package testSpring;import org.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;import com.test.bean.Person;publicclass test {     publicstaticvoid main(String[] args){     ApplicationContext ctx =newClassPathXmlApplicationContext("bean.xml");//读取bean.xml的内容     Person p =ctx.getBean("person",Person.class);//创建bean的引用对象     p.info();   }}

(5)执行结果

睡你麻痹起来嗨!name:baymax age:10


0 0
原创粉丝点击