POM
Create a project called hello-spring
project pom.xml
file as follows:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 7 <groupId>com.snake</groupId> 8 <artifactId>hello-spring</artifactId> 9 <version>1.0.0-SNAPSHOT</version> 10 <packaging>jar</packaging> 11 12 <dependencies> 13 <dependency> 14 <groupId>org.springframework</groupId> 15 <artifactId>spring-context</artifactId> 16 <version>4.3.17.RELEASE</version> 17 </dependency> 18 </dependencies> 19 </project>
Creating an interface and implementation
# Creating UserService
interfaces
1 package com.snake.hello.spring.service; 2 3 public interface UserService { 4 public void sayHi(); 5 }
Creating UserServiceImpl
achieve
package com.snake.hello.spring.service.impl; import com.snake.hello.spring.service.UserService; public class UserServiceImpl implements UserService { public void sayHi() { System.out.println("Hello Spring"); } }
# Create a Spring configuration file
In src/main/resources
Creating directory spring-context.xml
profiles, from now instantiate the class work to the Spring container management (IoC), the configuration file as follows:
<?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="userService" class="com.funtl.hello.spring.service.impl.UserServiceImpl" /> </beans>
-
<bean />
: Used to define an instance of the object. One example of a bean element corresponds. -
id
: This attribute is a unique identifier Bean instance, to access the id attribute Bean, Bean and dependencies between Bean is also associated with the id attribute. -
class
: Bean belongs to the specified class, pay attention here can only be a class, not an interface.
# Test Spring IoC
Create a MyTest
test class, can be created if the test object by Spring, code is as follows:
package com.snake.hello.spring; import com.snaek.hello.spring.service.UserService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyTest { public static void main(String[] args) { // 获取 Spring 容器 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-context.xml"); // 从 Spring 容器中获取对象 UserService userService = (UserService) applicationContext.getBean("userService"); userService.sayHi(); } }