spring入门程序编写

1、导入jar包

 

IoC基本上面的jar就可以实现了。加入springframework.aop是为了注解的实现

在3.2.2之后asm.jar并入了spring.core

logg的是日志包

2、普通java类的建立

package com.Model;

public class Dog {
    private String name;
    private int age;
    
    public void shou(){
        System.out.println("旺旺");
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    

}
View Code

3.spring配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           ">

    <bean id="dog" class="com.Model.Dog" />
</beans>
View Code

4、初始化spring容器并获取spring容器管理的java类的实例

方法一:

public void testContext(){
        ApplicationContext ac=
            new ClassPathXmlApplicationContext("com/test/applicationContext.xml");
        Dog dog=(Dog) ac.getBean("dog");
        dog.shou();
    }
View Code

方法二:(不常用,了解下)

    public void testFactory(){
        ResourcePatternResolver rpt=new PathMatchingResourcePatternResolver();
        Resource resource=rpt.getResource("com/test/applicationContext.xml");
        BeanFactory bf=new XmlBeanFactory(resource);
        Dog dog=(Dog) bf.getBean("dog");
        dog.shou();
    }
View Code

 

posted @ 2016-05-03 17:13  guodaxia  阅读(299)  评论(0编辑  收藏  举报