[Spring Study Notes] [EL used in Bean 5.4]

Source: Internet
Author: User

5.4.1 xml style Configuration

SpEL supports injection when Bean is defined. The "# {SpEL expression}" is used by default. The "# root" root object can be considered as ApplicationContext by default. SpEL is supported by only ApplicationContext, retrieving the root object attribute is actually obtaining the Bean in the container.

First, let's take a look at the configuration method chapter5/el1.xml:


Java code:
<Bean id = "world" class = "java. lang. String"> <constructor-arg value = "# {'World! '} "/> </Bean> <bean id =" hello1 "class =" java. lang. string "> <constructor-arg value =" # {'hello' }#{ world} "/> </bean> <bean id =" hello2 "class =" java. lang. string "> <constructor-arg value =" # {'hello' + world} "/> <! -- Nested --> <! -- <Constructor-arg value = "# {'hello' # {world}"/> --> </bean> <bean id = "hello3" class = "java. lang. string "> <constructor-arg value =" # {'hello' + @ world} "/> </bean>

By default, the template starts with "# {" and ends with "}" and does not allow nesting. For example, "# {'hello' # {world}" is incorrect, for example, "world" in "# {'hello' + world}" is parsed as Bean by default. Of course, you can use "@ bean" to reference it.


Next, let's test it:


Java code:
@Test public void testXmlExpression() {     ApplicationContext ctx = new ClassPathXmlApplicationContext("chapter5/el1.xml");     String hello1 = ctx.getBean("hello1", String.class);     String hello2 = ctx.getBean("hello2", String.class);     String hello3 = ctx.getBean("hello3", String.class);     Assert.assertEquals("Hello World!", hello1);     Assert.assertEquals("Hello World!", hello2);     Assert.assertEquals("Hello World!", hello3); }

Isn't it easy? In addition to the XML configuration method, Spring also provides an annotation method @ Value. Let's take a look.

5.4.2 annotation style Configuration

The SpEL configuration based on the annotation style is also very simple. Use the @ Value annotation to specify the SpEL expression. This annotation can be placed on fields, methods, and method parameters.

The test Bean class is as follows. Use @ Value to specify the SpEL expression:


Java code:
Package cn. javass. spring. chapter5; import org. springframework. beans. factory. annotation. value; public class SpELBean {@ Value ("# {'hello' + world}") private String value; // if the length of setter and getter is omitted, write it on your own}

First, check the configuration file (chapter5/el2.xml ):


Java code:
<?xml version="1.0" encoding="UTF-8"?> <beans  xmlns="http://www.springframework.org/schema/beans"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xmlns:context="http://www.springframework.org/schema/context"         xsi:schemaLocation="           http://www.springframework.org/schema/beans           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">    <context:annotation-config/>    <bean id="world" class="java.lang.String">        <constructor-arg value="#{' World!'}"/>    </bean>    <bean id="helloBean1" class="cn.javass.spring.chapter5.SpELBean"/>    <bean id="helloBean2" class="cn.javass.spring.chapter5.SpELBean">        <property name="value" value="haha"/>    </bean> </beans>

You must use"<Context: annotation-config/>To enable annotation support.


Start the test with the configuration file:

Java code:

@Test public void testAnnotationExpression() {     ApplicationContext ctx = new ClassPathXmlApplicationContext("chapter5/el2.xml");     SpELBean helloBean1 = ctx.getBean("helloBean1", SpELBean.class);     Assert.assertEquals("Hello World!", helloBean1.getValue());     SpELBean helloBean2 = ctx.getBean("helloBean2", SpELBean.class);     Assert.assertEquals("haha", helloBean2.getValue()); }

The "helloBean1" Value is the Value of the SpEL expression, while "helloBean2" is the Value injected through setter. This indicates that setter injection will overwrite the Value of @ Value.


5.4.3 SpEL problems in Bean Definition

If someone asks "# {I am not a SpEL expression}", not a SpEL expression, but a template inside the company, how can I change the prefix and suffix?

Let's take a look at how Spring uses the BeanExpressionResolver interface in the IoC container to evaluate the SpEL expression. If we get the implementation of this interface in some way and then modify the prefix and suffix, we can't.

Here, we use the BeanFactoryPostProcessor interface to provide the postProcessBeanFactory callback method, which is called by ApplicationContext when the IoC container is created but no Bean Initialization is performed, therefore, it is safe to delete the SpEL prefix and suffix at this stage. The specific code is as follows:


Java code:

package cn.javass.spring.chapter5; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.expression.StandardBeanExpressionResolver; public class SpELBeanFactoryPostProcessor implements BeanFactoryPostProcessor {     @Override     public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)         throws BeansException {         StandardBeanExpressionResolver resolver = (StandardBeanExpressionResolver) beanFactory.getBeanExpressionResolver();         resolver.setExpressionPrefix("%{");         resolver.setExpressionSuffix("}");     } }

First, get the BeanExpressionResolver implementation through the getBeanExpressionResolver method of ConfigurableListableBeanFactory, and then forcibly convert the type to StandardBeanExpressionResolver, which is the default Implementation of Spring, and then get rid of the prefix.


Start the test. First, prepare the configuration file (chapter5/el3.xml ):


Java code:

<?xml version="1.0" encoding="UTF-8"?> <beans  xmlns="http://www.springframework.org/schema/beans"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xmlns:context="http://www.springframework.org/schema/context"         xsi:schemaLocation="            http://www.springframework.org/schema/beans            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd            http://www.springframework.org/schema/context            http://www.springframework.org/schema/context/spring-context-3.0.xsd">    <context:annotation-config/>    <bean class="cn.javass.spring.chapter5.SpELBeanFactoryPostProcessor"/>    <bean id="world" class="java.lang.String">        <constructor-arg value="%{' World!'}"/>    </bean>    <bean id="helloBean1" class="cn.javass.spring.chapter5.SpELBean"/>    <bean id="helloBean2" class="cn.javass.spring.chapter5.SpELBean">        <property name="value" value="%{'Hello' + world}"/>    </bean> </beans>

The configuration file and the annotation style are almost the same. Only the SpEL expression prefix is changed to "% {" and the "cn. javass. spring. chapter5.SpELBeanFactoryPostProcessor "Bean, used to modify the prefix and suffix.

Test the code by writing the test code:


Java code:
@Test public void testPrefixExpression() {     ApplicationContext ctx = new ClassPathXmlApplicationContext("chapter5/el3.xml");     SpELBean helloBean1 = ctx.getBean("helloBean1", SpELBean.class);     Assert.assertEquals("#{'Hello' + world}", helloBean1.getValue());     SpELBean helloBean2 = ctx.getBean("helloBean2", SpELBean.class);     Assert.assertEquals("Hello World!", helloBean2.getValue()); }

In helloBean1, the result of "# {'hello' + world}" injected by @ Value or "# {'hello' + world}" indicates that SpEL expressions are not evaluated, helloBean2 injects "% {'hello' + world}" to get the correct "" Hello World! ".

This article from the "CEO Road" blog, please be sure to keep this source http://zhaohaibo.blog.51cto.com/7808533/1285940

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.