项目结构:
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" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 组件扫描功能,扫描指定的包路径 -->
<context:component-scan base-package="com.mazh" />
</beans>
实现类
@Component
public class HelloServiceImpl implements HelloService{
@Override
public void sayHello(String name) {
System.out.println("hello:" + name);
}
}
记得加上注解:@Component
测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring.xml")
public class JunitTest {
@Autowired
private HelloService helloService;
@Test
public void test() {
helloService.sayHello("hi");
}
}
注入注解:@Autowired/@Resource