IDEA
<properties>
<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 在需要创建对象的类上添加注解
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();
}
}
总结注解