This article uses the step-by-step way to carry on the explanation, later the article has been slightly written.
New Java Project
Open Eclipse. File->new->java Project
Fill in the project basic information, here we only need to provide the project name can
Click Finish, should appear similar to the following interface
Adding dependent jar Packages
Right-click on the Hellospring project and follow the instructions
In the pop-up window, Libraries tab, select Add External Jars
Add the following jar package:
Create a source file
Create the Com.tutorialspoint package as follows:
Fill in the package name in the popup window
Click Finish.
Create the Helloworld.java in the package com.tutorialspoint. Right-click on the package and proceed as follows
Write the class name in the popup window
Enter the following code in the Helloworld.java class file:
Package Com.tutorialspoint; Public class HelloWorld { private String message; Public void setmessage (String message) { this.message = message; } Public void GetMessage () { System.out.println ("Your message:" + message);} }
Create the Mainapp.java in the same way in the package Com.tutorialspoint, and enter the following code:
PackageCom.tutorialspoint;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext; Public classMainapp { Public Static voidMain (string[] args) {ApplicationContext context=NewClasspathxmlapplicationcontext ("Beans.xml"); HelloWorld obj= (HelloWorld) context.getbean ("HelloWorld"); Obj.getmessage (); }}
In Mainapp.java we need to pay attention to the following two points
- In the first step we first created the spring container, using an instance of the Classpathxmlapplicationcontext class to create the spring container.
When creating a spring container, the framework looks for beans.xml under the classpath and finally creates and initializes the container based on the contents of the Beans.xml.
The bean instance in the.
- In the second step we use the Getbean method of the container to get an instance of the container.
Creating a bean's configuration file
and enter the following in the newly created file:
<?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 http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd "> <BeanID= "HelloWorld"class= "Com.tutorialspoint.HelloWorld"> < Propertyname= "message"value= "Hello world!"/> </Bean>
</Beans>
Run
[Translate]5-spring Hello World