一点博主虽然是PHP出身,但是对Spring框架也有了解使用,Spring中的依赖注入原理和PHP中一些框架原理极为相似,都是采用反射机制,进行实例化获取对象,本文通过applicationContext.xml实现注入:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean name="c" class="com.game.spring.Test"> <property name="name" value="Test 1" /> </bean> <bean name="b" class="com.game.spring.Middent"> <!-- <property name="name" value="Test 1" /> --> </bean> <bean id="Plog" class="com.game.spring.Plog"/> <aop:config> <aop:pointcut id="loggerCutpoint" expression= "execution(* com.game.spring.Test.*(..)) "/> <aop:aspect id="logAspect" ref="Plog"> <aop:around pointcut-ref="loggerCutpoint" method="echo"/> </aop:aspect> </aop:config> </beans> <strong>参考代码:</strong> TestService类 package com.game.spring; import java.io.*; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestService { public static void main(String[] args) throws Exception{ ApplicationContext context = new ClassPathXmlApplicationContext( new String[] { "applicationContext.xml" }); Test c = (Test) context.getBean("c"); Middent b = (Middent) context.getBean("b"); c.getName(); b.getName(); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
Test类 public class Test { public String name; public void getName() { System.out.println("啊啊啊"); } public void setName(String name) { this.name = name; } } |
上面代码简单的对Test类进行配置注入,简单易懂。
一点博客,一点技术,每天一点分享
2018年4月14日 下午3:16 沙发
可以