Spring entry instance
The core concept of Spring is "dependency injection ". The so-called dependency injection is what you need. The Spring container will help you instantiate this object and then inject it into your application. In this way, you do not need to instantiate the dependency object by yourself, which not only simplifies development, but also decouples the dependencies of various modules. Next I will show an instance. For example, if the Person object wants to use the Computer, it must depend on the Computer object. Use Spring so that you do not need to use new objects. The Spring container will help you inject the Computer object as needed. In Spring, any java object can be used as a bean.
Person class:
Package com. ydoing. demo; public class Person {// dependent on the Computer object private Computer computer; // The Spring container automatically injects computer public void setComputer (Computer computer) {this. computer = computer;} public void useComputer () {computer. start ();}}
Computer Class:
Package com. ydoing. demo; // beanpublic class Computer {public void start () {System. out. println (computer run );}}
Bean Configuration:
Test class:
package com.ydoing.demo;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class test { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext(beans.xml); Person person = ctx.getBean(person, Person.class); person.useComputer(); }}
Console output:
July 19 9:25:05 am org. springframework. context. support. classPathXmlApplicationContext prepareRefresh information: Refreshing org. springframework. context. support. classPathXmlApplicationContext @ 64fe7a67: startup date [Sun Jul 19 09:25:05 CST 2015]; root of context hierarchy July 19, 2015 9:25:05 am org. springframework. beans. factory. xml. xmlBeanDefinitionReader loadBeanDefinitions information: Loading XML bean definitions from class path resource [beans. xml] computer run
Summary:
From the above program, we can see that there is no new keyword. When the person object requires a computer object, new is not required. Spring automatically injects the bean "computer" into "person.