spring Learn to create project Hello Spring instance code
- 2021-01-11 02:01:09
- OfStack
This paper mainly studies spring learning to create project Hello Spring example code, as follows.
1. Create eclipse project and introduce jar package
1, eclipse created java project HelloSpring
2. Create the lib directory and add the 5 jar packages required for spring
3, select 5 files, right - > Build Path - > add to build path
2. Write hello spring code for spring
1. Create the package ES34en.ES35en.ES36en and write ES37en.ES38en
package io.spring.beans;
/**
* @author Fat の ALEX E-mail:zanbin168@qq.com
* @version 1.0
*/
public class HelloWorld {
private String name;
public void setName(String name) {
this.name = name;
}
public void hello() {
System.out.println("hello " + name);
}
}
2, src right click - > Create spring bean configuration file applicationContext.xml
<?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">
<!-- configuration bean -->
<bean id="helloWorld" class="io.spring.beans.HelloWorld">
<property name="name" value=" Bright red "></property>
</bean>
</beans>
3. Write Main.java
package io.spring.beans;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author Fat の ALEX E-mail:zanbin168@qq.com
* @version 1.0
*/
public class Main {
public static void main(String[] args) {
//1 , create, Spring the IOC Container object
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//2 And from the IOC Fetching in the container Bean The instance
HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld");
//3 , call hello methods
helloWorld.hello();
}
}
The output
When spring logs are printed in red, it means that spring has been successfully applied
conclusion
The above is this article about spring learning to create project Hello Spring example code of all the content, I hope to help you. Interested friends can continue to refer to the site of other related topics, if there are shortcomings, welcome to leave a message to point out. Thank you for your support!