利用spring的表达式语言注入bean

来源:互联网 发布:软件学报 期刊ccf 编辑:程序博客网 时间:2024/06/11 09:43

以下是xml版

applicationContext.xml

<bean id="bookBean" class="com.javacodegeeks.snippets.enterprise.Book"><property name="id" value="12345" /><property name="title" value="Le Petit Prince (The Little Prince)" /></bean> <bean id="authorBean" class="com.javacodegeeks.snippets.enterprise.Author"><property name="name" value="Antoine de Saint-Exupéry" /><property name="book" value="#{bookBean}" /><property name="bookTitle" value="#{bookBean.title}" /></bean>

package com.javacodegeeks.snippets.enterprise;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;public class Book {private long id;private String title;public long getId() {return id;}public void setId(long id) {this.id = id;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;} public String getBookInfo(String authorName){return authorName + " has writen the book " + title + ", with book id " + ""+ id + ".";}@Overridepublic String toString(){return title;}}

package com.javacodegeeks.snippets.enterprise;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;public class Author {                         private String name;private Book book;private String bookTitle;private String fullAuthorInfo;public String getName() {return name;}public void setName(String name) {this.name = name;}public Book getBook() {return book;}public void setBook(Book book) {this.book = book;}public String getBookTitle() {return bookTitle;}public void setBookTitle(String bookTitle) {this.bookTitle = bookTitle;}public String getFullAuthorInfo() {return fullAuthorInfo;}public void setFullAuthorInfo(String fullAuthorInfo) {this.fullAuthorInfo = fullAuthorInfo;}@Overridepublic String toString(){return name + " has writen the book : " + book + ". \n" + bookTitle + " is a wonderful title of a wonderful book.";}}

package com.javacodegeeks.snippets.enterprise;import org.springframework.context.ConfigurableApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class App {public static void main(String[] args) {ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");Author author = (Author) context.getBean("authorBean");System.out.println(author.toString());System.out.println(author.getFullAuthorInfo());context.close();}}

原文:http://examples.javacodegeeks.com/enterprise-java/spring/beans-spring/spring-expression-language-example/

源代码:http://pan.baidu.com/share/link?shareid=598250216&uk=3878681452