Auto-cast Spring Beans

2019-02-05 05:47发布

Is there a way to auto-cast Spring beans to the class defined in the application context XML? I'd like to avoid putting type information about the beans in 2 places.... in the xml configuration file and also in the code as a cast.

For instance, given this config file

<bean id="bean-name" class="SimpleSpringBean"  scope="prototype">
    <property name="myValue" value="simple value"></property>
</bean>

Can I call ApplicationContext.getBean("bean-name") in such a way as to avoid directly casting the return type to SimpleStringBean. I know I can also call ApplicationContext.getBean("bean-name", SimpleSpringBean.class) to avoid the cast itself, but I still have the type info in 2 places.

It seems that Spring can get the class info (ApplicationContext.getType) or by getting the type from the bean itself, but no way to automatically cast the type without programmer intervention.

6条回答
淡お忘
2楼-- · 2019-02-05 05:57

What if I use Spring as an object factory that my application uses extensively. That is, instead of writing a bunch of classes that already inherit or wrap around known Java classes I just decide to move all that into an xml file to cut down on lines of Java code. This will mean many lines of xml but I won't need to make skeleton Java classes which I inject with Spring or autowire. Thus making the lines of Java code less.

For this reason and still as I am new to Spring I have just as stated in previous posts used static Java methods which wrap around the getBeans().

I have worked with Spring but it is still new to me so forgive my question.

查看更多
叛逆
3楼-- · 2019-02-05 06:06

I agree with Sii, you should avoid calling getBean as much as you can. Just wire your beans to classes that depends on them.

Still, if you have a single class that holds the application context, you can provide a wrapper generic method like the following:

class MyContextHolder{
    ApplicationContext appContext;
    ......
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName)
    {
        return (T)appContext.getBean(beanName);
    }
}

Then you can call it without casting

MyClass mc = MyContextHolder.getBean("myClassBean");
查看更多
beautiful°
4楼-- · 2019-02-05 06:06

"Because Spring AOP is implemented using dynamic proxies, you nearly always want Spring to hand you an instance of an interface the bean implements (which could be an AOP proxy), not of the implementation class"

So there is no way to get a dynamic proxy using getBean(), then whats the best practice if there are no interfaces and its a stand alone driver class to be executed?

查看更多
Lonely孤独者°
5楼-- · 2019-02-05 06:08

The answer is you shouldn't be using ApplicationContext.getBean() at all if it's possible, and bear with the one place you have to in the bootstrap code. (Generally, you should never need to use getBean() outside of your application's entry points.)

Also, what you're asking is likely impossible in the Java language at all. Casting is a compile-time feature, combined with a runtime check. The return type of getBean() simply must be known at compile time. Even if Spring can determine the type of an object, it can't change its own method signatures at runtime.

Another thing is that even if this were possible, the feature wouldn't be all that useful. Because Spring AOP is implemented using dynamic proxies, you nearly always want Spring to hand you an instance of an interface the bean implements (which could be an AOP proxy), not of the implementation class.

查看更多
Summer. ? 凉城
6楼-- · 2019-02-05 06:11

The main reason for getBean being untyped is the compatibility of Spring (up to version 2.5.x) with Java 1.4. Spring 3.0 will drop that and thus offer typed getBean method then.

Nevertheless you should avoid looking up beans directly and minimize its usage as far as possible.

查看更多
劳资没心,怎么记你
7楼-- · 2019-02-05 06:12

Another approach I also use is autowiring the bootstrapping class using:

public class Main {
    @Autowired FooFacade foo;
    @Autowired BarFacade bar;

    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("appCtx.xml");
        AutowireCapableBeanFactory bf = ctx.getAutowireCapableBeanFactory();
        Object main = bf.createBean(Main.class, 
                                    AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT,
                                    false);
        ((Main) main).run();
    }

    private void run() {
        foo.doBootstrapStuff();
        bar.doMoreBootstrapStuff();
    }
}

(Code done from memory. Might only work if you have the Spring context configured to process wiring annotations, in that case making setters for foo and bar should work.)

查看更多
登录 后发表回答