spring入门程序编写
1、导入jar包
IoC基本上面的jar就可以实现了。加入springframework.aop是为了注解的实现
在3.2.2之后asm.jar并入了spring.core
logg的是日志包
2、普通java类的建立
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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; } }
3.spring配置文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?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>
4、初始化spring容器并获取spring容器管理的java类的实例
方法一:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public void testContext(){ ApplicationContext ac= new ClassPathXmlApplicationContext("com/test/applicationContext.xml"); Dog dog=(Dog) ac.getBean("dog"); dog.shou(); }
方法二:(不常用,了解下)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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(); }