Old*_*eon 6 java spring inner-classes superclass illegalaccessexception
我在Spring Controller中使用内部类.从它的父类超类访问受保护的字段/方法时遇到问题.
研究表明,这是由不同的类加载器在某种程度上造成的,但我不太了解Spring确定.
class SuperBaseController {
protected String aField;
protected void aMethod() {
}
}
@Controller
class OuterMyController extends SuperBaseController {
class Inner {
public void itsMethod() {
// java.lang.IllegalAccessError: tried to access method
aMethod();
}
public void getField() {
// java.lang.IllegalAccessError: tried to access field
String s = aField;
}
}
void doSomething () {
// Obviously fine.
aMethod();
// Fails in the Inner method call.
new Inner().itsMethod();
// Obviously fine.
String s = aField;
// Fails in the Inner method call.
new Inner().getField();
}
}
Run Code Online (Sandbox Code Playgroud)
有没有简单的技术来避免/解决这个问题?优选地,不涉及制造田地/方法的那些public.
我已经确认ClassLoader外部类的属性与超类的属性不同.
我创建了以下类:
public class BaseController
{
protected String field;
protected void method()
{
System.out.println("I'm protected method");
}
}
@RestController
@RequestMapping("/stack")
public class StackController extends BaseController
{
class Inner
{
public void methodInvocation()
{
method();
}
public void fieldInvocation()
{
field = "Test";
}
}
@RequestMapping(value= {"/invoca"}, method= {RequestMethod.GET})
public ResponseEntity<String> invocation()
{
Inner in = new Inner();
in.fieldInvocation();
in.methodInvocation();
return new ResponseEntity<String>("OK", HttpStatus.OK);
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试调用其余服务,但没有任何问题。现在我在 Spring 中使用这个配置(基于注释的注释):
@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages = { "it.spring.controller" })
@PropertySource( value={"classpath:config.properties"}, encoding="UTF-8", ignoreResourceNotFound=false)
public class DbConfig
{
}
@Configuration
@EnableWebMvc
@Import(DbConfig.class)
@PropertySource(value = { "classpath:config.properties" }, encoding = "UTF-8", ignoreResourceNotFound = false)
public class WebMvcConfig extends WebMvcConfigurerAdapter
{
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我使用了@Import注释,并在 web.xml 中使用了以下配置:
<servlet>
<servlet-name>SpringDispSvlt</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>it.WebMvcConfig</param-value>
</init-param>
<init-param>
<param-name>dispatchOptionsRequest</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
Run Code Online (Sandbox Code Playgroud)
通过使用此配置,我在调用内部类中的受保护字段和/或方法时没有任何问题
如果您无法调整您的配置以适应此配置..您可以发布您使用的配置吗?
我希望它有用
安吉洛
| 归档时间: |
|
| 查看次数: |
580 次 |
| 最近记录: |