一、首先需要引入jar包:spring-aop-4.2.4.RELEASE.jar。(在spring解压包libs内)。
二、如果注解方式注入依赖的对象,需要引用新的约束。
内的:xsd-configuration.html。打开网页中的:the context schema 粘贴复制:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" 5 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 6 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- bean definitions here --> 7 8 </beans>
写接口和实现类:
1 package jd.com.inject; 2 3 public interface Indemo { 4 void save(); 5 }
实现类:需要写注解:@Component(value = "indemo") 其中value是配置文件中的id值,在调用的时候执行方法getbean(id值)调用就是这个值。
1 package jd.com.inject; 2 3 4 import org.springframework.stereotype.Component; 5 6 @Component(value = "indemo") 7 public class indemoIpl implements Indemo { 8 @Override 9 public void save() { 10 System.out.println("调用业务层。"); 11 } 12 }
配置文件(applicationContenxt.xml)
需要开启扫描组件:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" 5 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 6 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- bean definitions here --> 7 8 9 <context:component-scan base-package="jd.com" /> 10 11 </beans>
其中:
<context:component-scan base-package="jd.com" /> 其中base-package是需要扫描的包。需要注意:这里写的是jd.com而不是完整的包。这样涵盖所有包。
测试类:
1 package jd.com.inject; 2 3 import org.junit.Test; 4 import org.springframework.context.ApplicationContext; 5 import org.springframework.context.support.ClassPathXmlApplicationContext; 6 7 public class TestDemo { 8 @Test 9 public void testdemo(){ 10 ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml"); 11 indemoIpl in= (indemoIpl) ac.getBean("indemo"); 12 in.save(); 13 } 14 15 16 }
这样就是实现注解方式注入。
原文地址:https://www.cnblogs.com/evilliu/p/8868547.html
时间: 2024-11-02 03:14:48