我有一个扩展其他 Java 文件的 bean。当我创建 Spring bean 时,所有公共(public)方法(来 self 的文件和扩展文件)都会公开。如何在 bean XML 配置中隐藏不需要的方法,使它们不被暴露?
添加说明:
我通过 RDS for Flex 应用程序公开我的 Bean。所以,我的 bean 可以通过网络获得。使用不需要的方法我有两个问题:
- 安全性 - 任何人都可以调用我从 JdbcDaoSupport 继承的 setDataSource 或其他任何东西..我认为这太疯狂了:-)
- 因为我使用 RDS for Flex Builder,它会自动为我的 Flex 应用程序创建远程对象。像 setDataSource 这样的所有方法都可以在我的 Flex 应用程序中使用。这不好。当然我可以把它们剪掉,但第一点仍然存在。
最佳答案
如果继承的方法不应该被访问,也许你应该使用聚合而不是继承?
由于任何代码都可以调用该对象上的公共(public)继承方法,因此这不是 Spring 特有的。
编辑:正如您自己发现的那样,远程处理框架可以配置为不公开所有方法。如果不可能,您可以使用:
import java.lang.reflect.Proxy;
public static <I> I restrictToInterface(final I instance, Class<I> publicInterface) {
Object proxy = Proxy.newProxyInstance(
publicInterface.getClassLoader(),
new Class<?>[] {publicInterface},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(instance, args);
}
}
);
return publicInterface.cast(proxy);
}
测试代码:
interface MyRemoteInterface {
void foo(Object bar);
}
class MyBeanImpl implements MyRemoteInterface {
@Override
public void foo(Object bar) {
System.out.println(bar);
}
public void dangerousMethodThatMustNotBeInvoked() {
// launch missiles
}
}
public static void main(String[] args) {
MyBeanImpl beanImpl = new MyBeanImpl();
MyRemoteInterface remotableBean = restrictToInterface(beanImpl, MyRemoteInterface.class);
System.out.println("Remoteable Methods are:");
for (Method m : remotableBean.getClass().getMethods()) {
if (!Modifier.isStatic(m.getModifiers())) {
System.out.println("\t" + m.getName());
}
}
remotableBean.foo("Hello world!");
}
关于java - 如何对 Spring bean 隐藏方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3125040/