spring 上下文获取bean,service等类

spring工程里,在controller,service以外的普通类里获取service,bean等类,可以通过上下文环境 ApplicationContext 做到。

见证奇迹的时刻到了:


private static ApplicationContext applicationContext = new FileSystemXmlApplicationContext("classpath:spring-context.xml");     

private ISmsService smsService = applicationContext.getBean(ISmsService.class);


注意:classpath:spring-context.xml,这里的配置文件位置一定要写正确,否则读取不到配置文件,当然就拿不到类了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Spring AOP 中,配置上下文可以通过以下步骤完成: 1. 在 Spring 配置文件中引入 aop 命名空间,如下所示: ```xml <beans xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> ``` 2. 定义切面,其中包含切点和通知的定义。例如,创建一个名为 `LoggingAspect` 的切面: ```java public class LoggingAspect { // 定义切点 @Pointcut("execution(* com.example.service.*.*(..))") private void serviceMethods() {} // 定义前置通知 @Before("serviceMethods()") public void beforeAdvice() { System.out.println("Before advice executed!"); } // 定义后置通知 @After("serviceMethods()") public void afterAdvice() { System.out.println("After advice executed!"); } } ``` 3. 在 Spring 配置文件中配置切面bean: ```xml <bean id="loggingAspect" class="com.example.aspect.LoggingAspect" /> ``` 4. 配置 AOP 代理,将切面应用到目标对象上。可以使用 `<aop:config>` 元素来配置代理。例如: ```xml <aop:config> <aop:aspect ref="loggingAspect"> <aop:before method="beforeAdvice" pointcut-ref="serviceMethods" /> <aop:after method="afterAdvice" pointcut-ref="serviceMethods" /> </aop:aspect> </aop:config> ``` 在上述配置中,`ref` 属性指定了切面bean ID,`method` 属性指定了通知方法的名称,`pointcut-ref` 属性指定了切点的引用。 通过以上配置,你可以在目标对象的方法执行前后执行相应的通知方法。注意,上述示例中的切点表达式是一个简单的示例,你需要根据实际情况进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值