04 Hello Word
阿新 • • 發佈:2018-11-12
1. 建立Maven工程,並引入JAR
JAR 包引入
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
建立Spring核心配置檔案
spring.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">
</ beans>
建立類
DAO 層
package com.javaee.spring.dao;
public class ExampleDao {
public void save() {
System.out.println("------ dao save() ------");
}
}
Service 層
package com.javaee.spring.service;
import com.javaee.spring.dao.ExampleDao;
public class ExampleService{
private ExampleDao exampleDao;
public void save() {
System.out.println("------ service save() ------");
exampleDao.save();
}
public void setExampleDao(ExampleDao exampleDao) {
this.exampleDao = exampleDao;
}
}
註冊Bean
<bean id="exampleService" class="com.javaee.spring.service.ExampleService">
<property name="exampleDao" ref="exampleDao" />
</bean>
<bean id="exampleDao" class="com.javaee.spring.dao.ExampleDao"></bean>
測試
public class ExampleBeanTest {
private ClassPathXmlApplicationContext context;
private ExampleService exampleService;
@Before
public void init() {
context = new ClassPathXmlApplicationContext("spring.xml");
exampleService = (ExampleService) context.getBean("exampleService");
}
@Test
public void save() {
exampleService.save();
}
}