gpt4 book ai didi

java - 无法将方面应用于 String 类

转载 作者:行者123 更新时间:2023-12-02 02:07:27 25 4
gpt4 key购买 nike

我正在尝试使用 AspectJ。我尝试在 String 类上应用方面。我创建的 Spring 配置文件为:

<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"
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 ">

<!-- Enable @AspectJ annotation support -->
<aop:aspectj-autoproxy />

<!-- Employee manager -->
<bean id="employeeManager" class="com.test.advice.EmployeeManager" />

<!-- Logging Aspect -->
<bean id="loggingAspect" class="com.test.advice.LoggingAspect" />

<bean id="bean1" class="java.lang.String">
<constructor-arg value="abx" />
</bean>

</beans>

然后是一个 Aspect 类,

package com.test.advice;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class LoggingAspect
{

@Around("execution(* java.lang.String.*(..))")
public void logAroundGetEmployee(ProceedingJoinPoint joinPoint) throws Throwable
{
System.out.println("works");
}
}

之后创建了一个具有主要方法的类,例如:

package com.test.advice;

package com.test.advice;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AspectJAutoProxyTest
{
public static void main(String[] args)
{
ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Customer.xml");

String pqr = (String) context.getBean("bean1");

pqr.trim();

}
}

运行时它应该向控制台输出“works”。但它没有说,

Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy5 cannot be cast to java.lang.String
at com.test.advice.AspectJAutoProxyTest.main(AspectJAutoProxyTest.java:13)

有什么问题吗?我们不能对 java.lang 对象应用代理吗?请帮忙。

最佳答案

要使用代理对象代替真实对象,代理对象必须是真实对象的子类。 Stringfinal,JVM 不允许创建这样的子类。

(请注意,spring 有两种代理模式;一种创建实际的子类,另一种仅实现所有公共(public)接口(interface)。您可能正在使用后者,但如果更改为前者,您会在代理处看到异常创建时间)

关于java - 无法将方面应用于 String 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50551489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com