The main research in this article is the Hello Spring instance code for creating a project in spring learning, as follows.
1. eclipse creates java project HelloSpring
2. Create a lib directory and add 5 jar packages required for spring
3. Select 5 files, right-click -> Build Path -> add to build path
1. Create the package io.spring.beans and write HelloWorld.java
package io.spring.beans;/** * @author ALEX E-mail:[email protected] * @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. Right-click src-> 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"> <!-- Configure bean --> <bean id="helloWorld"> <property name="name" value="Big Red"></property> </bean> </beans>
3. Write Main.java
package io.spring.beans;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * @author PangpangのALEX E-mail:[email protected] * @version 1.0 */public class Main {public static void main(String[] args) {//1. Create Spring IOC container object ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");//2. Get Bean instance from the IOC container HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld");//3. Call the hello method helloWorld.hello();}}
Output result
When a red spring log is printed in the console, it means that the spring application is successful
The above is the entire content of this article about the Hello Spring instance code for creating a project in spring learning. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!