IDEAjava
spring
app
maven
測試
spa
component
<properties>xml
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
2 配置文件 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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--開啓註解 定義掃描包 context:component-scn
context 名稱空間 引入約束
base-package指定要掃描的包 掃描本包和其子包
-->
<context:component-scan base-package="cn.kgc"></context:component-scan>
</beans>
3 在須要建立對象的類上添加註解ci
package cn.kgc.service.impl;
import cn.kgc.dao.UserDao;
import cn.kgc.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @author lijun
* @date 2019/7/4 9:00
*/
@Service
public class UserServiceImpl implements UserService {
@Resource()
UserDao userDao;
public void print() {
userDao.print();
}
}
4 測試
package cn.kgc;
import cn.kgc.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
2 * @author lijun
* @date 2019/7/4 9:03
*/
public class TestAnn {
@Test
public void test() {
// 建立容器
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = ac.getBean(UserService.class);
// 獲取對象
userService.print();
}
}
總結註解