0, written in the preceding words this article, in a simple example, describes spring's loading and fetching of Java classes through containers.in the following we can see that there is a Java class coder, we did not manually call new to instantiate, but from the spring container applicationcontext to get the instantiation of the class object。
1. Build a spring project with Maven
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.16.RELEASE</version>
</dependency>
</dependencies>
Using MAVEN to build a project, Dependency,ide automatically downloads associated spring-related core packages, such as: 2, to create a simple Java class by spring's official offer.
public class Coder {
private String name;
private int age;
public void print(){
System.out.println("Hello World");
}
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. Create a spring configuration file for idea, Pom.xml has already configured spring dependencies, so when creating a new spring configuration file, you can create the most basic configuration file directly from idea: Then configure the Java class Bean:
<?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="Coder" class="Dulk.learn.spring.Coder"></bean>
</beans>
4, initialize the container, get the instance spring provides a variety of ways to initialize containers, the most common of which are two:
- Beanfactory, early JavaBean factory class implementation ( not recommended )
- ApplicationContext, the extension of beanfactory, provides more functions, such as internationalization processing, bean automatic assembly, etc.
beanfactory:
public class Test {
public static void main(String[] args) {
- Beanfactory
ResourcePatternResolver rpt = new PathMatchingResourcePatternResolver();
Resource resource = rpt.getResource("/applicationContext.xml");
BeanFactory bf = new XmlBeanFactory(resource);
Coder coder = (Coder) bf.getBean("coder");
coder.print();
}
}
ApplicationContext:
public class Test {
public static void main(String[] args) {
- ApplicationContext
ApplicationContext ac = new ClassPathXmlApplicationContext("/applicationContext.xml");
Coder coder = (Coder) ac.getBean("coder");
coder.print();
}
}
[] Spring "Hello World"