涉及到的类包括:
1. ITestService.java
2. TestServiceImp.java
3. autoWiringService.java
以及Spring配置文件:
4.autoWiring.xml
对应的源码为:
1. ITestService.java
package com.z.test.annotation;
/**
* Created by Z on 2016/11/16.
*/
public interface ITestService {
public void annoTest();
}
2.TestServiceImp.java
package com.z.test.annotation;
import org.springframework.stereotype.Service;
/**
* Created by Z on 2016/11/16.
* 如何引入注解
*/
@Service("testServiceImp")
public class TestServiceImp implements ITestService {
public void annoTest(){
System.out.println("注解调用");
}
}
3.autoWiringService.java
package com.z.test.annotation;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.annotation.Resource;
/**
* Created by Z on 2016/11/16.
*/
public class AutoWiringService {
@Resource(name ="testServiceImp")
public ITestService iTestService;
public void autoTest(){
iTestService.annoTest();
}
public static void main(String[] args){
ApplicationContext context =new ClassPathXmlApplicationContext("autowiring.xml");
AutoWiringService autoW=(AutoWiringService)context.getBean("autoWiringService");
autoW.autoTest();
}
}
使用了@Service 和 @Resource注解。目录结构:
在AutoWiringService运行主方法进行测试时,总是有错误如下:
猜测是否是无法读取xml文件?还是哪里没有配置好?
autoWiring.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:cotent="http://www.springframework.org/schema/cache"
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/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/context
">
<!--Bean的自动装配-->
<!--<bean id="autoWiringDAO" class="com.z.autowiring.AutoWiringDAO" />-->
<bean id="autoWiringService" class="com.z.test.annotation.AutoWiringService" />
<!-- 扫描 哪些包或者类 需要用到注解 -->
<context:component-scan base-package="com.z.test.annotation" />
<!-- 使用注解 -->
<cotent:annotation-driven/>
</beans>
你在web.xml中配置了吗,检查一下,那边很重要
spring的配置文件是什么样的呢,有没有配置注解扫描的包?