Spring框架提供了一种较好的实现模块复用和解耦的方式,即控制反转(Inversion of Control, IOC)。IOC原则将对象的初始化、依赖注入、装配和生命周期管理交给IOC容器来处理,即将控制权交由容器。容器根据用户的配置规则来管理容器中的对象,这个配置规则表现为xml配置文件、注解或java代码。
<?xml version="1.0" encoding="UTF-8"?> <beansxmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <beanid="dog1"class="com.pojo.Dog"> <!-- collaborators and configuration for this bean go here --> </bean> <beanid="..."class="..."> <!-- collaborators and configuration for this bean go here --> </bean> <!-- more bean definitions go here --> </beans>
// 通过xml配置文件获取容器 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); // 通过id获取容器中的Bean Dog dog = context.getBean("dog1", Dog.class)
package examples; publicclassExampleBean{ // Number of years to calculate the Ultimate Answer privatefinalint years; // The Answer to Life, the Universe, and Everything privatefinal String ultimateAnswer;
<beanid="exampleBean"class="examples.ExampleBean"> <!-- setter injection using the nested ref element --> <propertyname="beanOne"> <refbean="anotherExampleBean"/> </property> <!-- setter injection using the neater ref attribute --> <propertyname="beanTwo"ref="yetAnotherBean"/> <propertyname="integerProperty"value="1"/> </bean>
<beanid="moreComplexObject"class="example.ComplexObject"> <!-- results in a setAdminEmails(java.util.Properties) call --> <propertyname="adminEmails"> <props> <propkey="administrator">administrator@example.org</prop> <propkey="support">support@example.org</prop> <propkey="development">development@example.org</prop> </props> </property> <!-- results in a setSomeList(java.util.List) call --> <propertyname="someList"> <list> <value>a list element followed by a reference</value> <refbean="myDataSource" /> </list> </property> <!-- results in a setSomeMap(java.util.Map) call --> <propertyname="someMap"> <map> <entrykey="an entry"value="just some string"/> <entrykey="a ref"value-ref="myDataSource"/> </map> </property> <!-- results in a setSomeSet(java.util.Set) call --> <propertyname="someSet"> <set> <value>just some string</value> <refbean="myDataSource" /> </set> </property> </bean>