EJB 3.1 教程 |
学习笔记(转载 http://jerry-wu.gicp.net/) |
MashupEye |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <extensions> <extension module="org.jboss.as.clustering.infinispan"/> <extension module="org.jboss.as.connector"/> <extension module="org.jboss.as.deployment-scanner"/> <extension module="org.jboss.as.ee"/> <extension module="org.jboss.as.ejb3"/> <extension module="org.jboss.as.jaxrs"/> <extension module="org.jboss.as.jmx"/> <extension module="org.jboss.as.jpa"/> <extension module="org.jboss.as.logging"/> <extension module="org.jboss.as.naming"/> <extension module="org.jboss.as.osgi"/> <extension module="org.jboss.as.remoting"/> <extension module="org.jboss.as.sar"/> <extension module="org.jboss.as.security"/> <extension module="org.jboss.as.threads"/> <extension module="org.jboss.as.transactions"/> <extension module="org.jboss.as.web"/> <extension module="org.jboss.as.weld"/> </extensions> |
1 2 3 4 | <subsystem xmlns="urn:jboss:domain:datasources:1.0"> <datasources> <datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="ExampleDS"> |
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1</connection-url> <driver>h2</driver> <pool> <min-pool-size>10</min-pool-size> <max-pool-size>20</max-pool-size> <prefill>true</prefill> </pool> <security> <user-name>sa</user-name> <password>sa</password> </security> </datasource> <xa-datasource jndi-name="java:jboss/datasources/ExampleXADS" pool-name="ExampleXADS"> <driver>h2</driver> <xa-datasource-property name="URL">jdbc:h2:mem:test</xa-datasource-property> <xa-pool> <min-pool-size>10</min-pool-size> <max-pool-size>20</max-pool-size> <prefill>true</prefill> </xa-pool> <security> <user-name>sa</user-name> <password>sa</password> </security> </xa-datasource> <drivers> <driver name="h2" module="com.h2database.h2"> <xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class> </driver> </drivers> </datasources> </subsystem> |
1 2 3 4 5 6 7 8 9 10 | @Stateless public class BookEJB { …… public Book findBookById(Long id) { …… } public Book createBook(Book book) { …… } } |
1 2 | @EJB private static BookEJB bookEJB; |
1 2 3 4 5 | @Singleton @Startup public class CacheEJB { // ... } |
1 2 3 4 5 6 7 8 9 10 | @Singleton public class CountryCodeEJB { ... } @DependsOn("CountryCodeEJB") @Singleton public class CacheEJB { ... } |
1 2 3 4 5 6 | @Singleton public class CountryCodeEJB { ... } @Singleton |
7 8 9 10 11 12 13 14 15 | public class ZipCodeEJB { ... } @DependsOn("CountryCodeEJB", "ZipCodeEJB") @Singleton public class CacheEJB { ... } |
1 2 3 4 5 | @DependsOn("business.jar#CountryCodeEJB") @Singleton public class CacheEJB { ... } |
1 2 3 4 5 6 7 | @Singleton @Lock(LockType.READ) public class CacheEJB { private Map<Long, Object> cache = new HashMap<Long, Object>(); public void addToCache(Long id, Object object) { if (!cache.containsKey(id)) |
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | cache.put(id, object); } public void removeFromCache(Long id) { if (cache.containsKey(id)) cache.remove(id); } @AccessTimeout(value = 20, unit = TimeUnit.SECONDS) @Lock(LockType.WRITE) public Object getFromCache(Long id) { if (cache.containsKey(id)) return cache.get(id); else return null; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | @Singleton @ConcurrencyManagement(ConcurrencyManagementType.BEAN) public class CacheEJB { private Map<Long, Object> cache = new HashMap<Long, Object>(); public synchronized void addToCache(Long id, Object object) { if (!cache.containsKey(id)) cache.put(id, object); } public synchronized void removeFromCache(Long id) { if (cache.containsKey(id)) cache.remove(id); } public Object getFromCache(Long id) { if (cache.containsKey(id)) return cache.get(id); else return null; } |
22 | } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | @Singleton public class CacheEJB { private Map<Long, Object> cache = new HashMap<Long, Object>(); @AccessTimeout(0) public void addToCache(Long id, Object object) { if (!cache.containsKey(id)) cache.put(id, object); } public void removeFromCache(Long id) { if (cache.containsKey(id)) cache.remove(id); } public Object getFromCache(Long id) { if (cache.containsKey(id)) return cache.get(id); else return null; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | @Local public interface ItemLocal { List findBooks(); List findCDs(); } @ Remote public interface ItemRemote { List findBooks(); List findCDs(); Book createBook(Book book); CD createCD(CD cd); } @Stateless public class ItemEJB implements ItemLocal, ItemRemote { ... } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public interface ItemLocal { List findBooks(); List findCDs(); } public interface ItemRemote { List findBooks(); List findCDs(); Book createBook(Book book); CD createCD(CD cd); } @Stateless @Remote (ItemRemote.class) @Local (ItemLocal.class) public class ItemEJB implements ItemLocal, ItemRemote { ... } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | @Local public interface ItemLocal { List findBooks(); List findCDs(); } @WebService public interface ItemSOAP { List findBooks(); List findCDs(); Book createBook(Book book); CD createCD(CD cd); } @Path(/items) public interface ItemRest { List findBooks(); } |
20 21 22 23 | @Stateless public class ItemEJB implements ItemLocal, ItemSOAP, ItemRest { ... } |
1 2 3 4 5 6 7 | @Stateless public class ItemEJB { ... } //客户端代码 @EJB ItemEJB itemEJB; |
1 2 3 4 5 6 7 8 9 10 | @Stateless @Remote (ItemRemote.class) @Local (ItemLocal.class) public class ItemEJB implements ItemLocal, ItemRemote { ... } // 客户端代码 @EJB ItemEJB itemEJB; // 部署的时候会抛出一个异常 @EJB ItemLocal itemEJBLocal; @EJB ItemRemote itemEJBRemote; |
1 2 3 4 | @Stateless @Remote (ItemRemote.class) @Local (ItemLocal.class) @LocalBean |
5 6 7 8 9 10 11 | public class ItemEJB implements ItemLocal, ItemRemote { ... } // 客户端代码 @EJB ItemEJB itemEJB; @EJB ItemLocal itemEJBLocal; @EJB ItemRemote itemEJBRemote; |
1 2 3 4 5 6 7 | package com.apress.javaee6; @Stateless @LocalBean @Remote (ItemRemote.class) public class ItemEJB implements ItemRemote { ... } |
1 2 3 4 5 6 7 8 9 10 11 | @Stateless public class ItemEJB { @Resource private SessionContext context; ... public Book createBook(Book book) { ... if (cantFindAuthor()) context.setRollbackOnly(); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | public class ItemEJBTest { private static EJBContainer ec; private static Context ctx; @BeforeClass public static void initContainer() throws Exception { ec = EJBContainer.createEJBContainer(); ctx = ec.getContext(); } @AfterClass public static void closeContainer() throws Exception { if (ec != null) ec.close(); } @Test public void shouldCreateABook() throws Exception { // 创建一个 book 的实例 Book book = new Book(); book.setTitle("The Hitchhiker's Guide to the Galaxy"); book.setPrice(12.5F); book.setDescription("Science fiction comedy book"); book.setIsbn("1-84023-742-2"); book.setNbOfPage(354); book.setIllustrations(false); // 查找 EJB ItemEJB bookEJB = (ItemEJB) ctx.lookup("java:global/classes/ItemEJB"); // 存储 book 到 EJB book = itemEJB.createBook(book); assertNotNull("ID should not be null", book.getId()); // 从数据库中查询所有 book |
33 34 35 36 | List<Book> books = itemEJB.findBooks(); assertNotNull(books); } } |
1 2 3 4 5 6 7 8 9 10 11 12 | @Stateless public class OrderEJB { @Asynchronous public void sendEmailOrderComplete(Order order, Customer customer) { // 发送 E-mail } @Asynchronous public void printOrder(Order order) { // 打印订单 } } |
1 2 3 4 | @Stateless @Asynchronous public class OrderEJB { @Resource |
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | SessionContext ctx; public void sendEmailOrderComplete(Order order, Customer customer) { // 发送 E-mail } public void printOrder(Order order) { // 打印订单 } public Future<Integer> sendOrderToWorkflow(Order order) { Integer status = 0; // 处理 status = 1; if (ctx.wasCancelCalled()) { return new AsyncResult<Integer>(2); } // 处理 return new AsyncResult<Integer>(status); } } |
1 2 | Future<Integer> status = orderEJB.sendOrderToWorkflow (order); Integer statusValue = status.get(); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <ejb-jar xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_1.xsd" version="3.1"> <enterprise-beans> <session> <ejb-name>ItemEJB</ejb-name> <ejb-class>com.apress.javaee6.ItemEJB</ejb-class> <local>com.apress.javaee6.ItemLocal</local> <local-bean/> <remote>com.apress.javaee6.ItemRemote</remote> <session-type>Stateless</session-type> <transaction-type>Container</transaction-type> <env-entry> <env-entry-name>aBookTitle</env-entry-name> <env-entry-type>java.lang.String</env-entry-type> <env-entry-value>Beginning Java EE 6</env-entry-value> </env-entry> </session> </enterprise-beans> </ejb-jar> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | @Stateless public class ItemEJB { @PersistenceContext(unitName = "chapter07PU") private EntityManager em; @EJB private CustomerEJB customerEJB; @WebServiceRef private ArtistWebService artistWebService; private SessionContext ctx; @Resource public void setCtx(SessionContext ctx) { this.ctx = ctx; } ... } |
1 2 3 4 5 6 7 8 | @Stateless public class ItemEJB { public Item convertPrice(Item item) { item.setPrice(item.getPrice() * 0.80); item.setCurrency("Euros"); return item; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <ejb-jar xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_1.xsd" version="3.1"> <enterprise-beans> <session> <ejb-name>ItemEJB</ejb-name> <ejb-class>com.apress.javaee6.ItemEJB</ejb-class> <env-entry> <env-entry-name>currencyEntry</env-entry-name> <env-entry-type>java.lang.String</env-entry-type> <env-entry-value>Euros</env-entry-value> </env-entry> <env-entry> <env-entry-name>changeRateEntry</env-entry-name> <env-entry-type>java.lang.Float</env-entry-type> <env-entry-value>0.80</env-entry-value> </env-entry> </session> </enterprise-beans> </ejb-jar> |
1 2 3 4 5 6 7 8 9 10 11 12 | @Stateless public class ItemEJB { @Resource(name = "currencyEntry") private String currency; @Resource(name = "changeRateEntry") private Float changeRate; public Item convertPrice(Item item) { item.setPrice(item.getPrice() * changeRate); item.setCurrency(currency); return item; } } |
属性 | 描述 | 可能值 | 默认值 |
second | 秒数(一分钟内可 以的秒数) | [0,59] | 0 |
minute | 分钟数(一小时内 可以的分钟数) | [0,59] | 0 |
hour | 小时数(一天内可 以的小时数) | [0,23] | 0 |
dayOfMonth | 天数(一个月内可 以的天数) | [1,31] 或者{"1st", "2nd", "3rd", . . . , "30th", "31st"} 或者{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"} 或者 "Last" (一个月的最后 一天) 或者 -x (一个月的倒数第 x 天) | * |
month | 月数(一年内的可 以的月数) | [1,12] 或者 {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"} | |
dayOfWeek | 一星期内的天数 | [0,7] 或者 {"Sun", "Mon", "Tue", "Wed", Thu", "Fri", "Sat"}—"0" 和"7" 都是指星期天 | * |
year | 特定的年份 | 一个四位数的年份 | * |
timezone | 特定的时区 | 由 zoneinfo(或 TZ)数据库提供的时区列表 |
形式 | 描述 | 例子 |
单个值 | 属性只有一个可能的值 | year = "2010" month= "May" |
通配符 | 属性所有可能的值 | second = "*" dayOfWeek = "*" |
列表 | 属性有多个值,以,隔开 | year = "2008,2012,2016" dayOfWeek ="Sat,Sun" minute = "0-10,30,40" |
范围 | 属性有在一定范围内的值,以-隔开 | second = "1-10". dayOfWeek = "Mon-Fri" |
增量 | 属性有一个起点和一个时间间隔,以/隔 开 | minute = "*/15" second = "30/10" |
例子 | 表达式 |
每周三的午夜 | dayOfWeek="Wed" |
每周三的午夜 | second="0", minute="0", hour="0", dayOfMonth="*", month="*", dayOfWeek="Wed", year="*" |
每个工作日的 6:55 | minute="55", hour="6", dayOfWeek="Mon-Fri" |
每个工作日的 6:55,巴黎时区 | minute="55", hour="6", dayOfWeek="Mon-Fri", timezone="Europe/Paris" |
每天每一小时的每一分钟 | minute="*", hour="*" |
每天每一小时每一分钟的每一秒 | second="*", minute="*", hour="*" |
每周一和周五的中午过后 30 秒 | second="30", hour="12", dayOfWeek="Mon, Fri" |
一小时中的每 5 分钟 | minute="*/5", hour="*" |
一小时中的每 5 分钟 | minute="0,5,10,15,20,25,30,35,40,45,50,55", hour="*" |
12 月最后一个星期一的下午 3 点 | hour="15", dayOfMonth="Last Mon", month="Dec" |
每个月倒数第 3 天的下午 1 点 | hour="13", dayOfMonth="-3" |
在每月的第二个星期二中午开始后每隔一 小时 | hour="12/2", dayOfMonth="2nd Tue" |
早上 1 点和 2 点时,每隔 14 分钟 | minute = "*/14", hour="1,2" |
早上 1 点和 2 点时,每隔 14 分钟 | minute = "0,14,28,42,56", our = "1,2" |
在 30 秒的时候开始,每隔 10 秒钟 | second = "30/10" |
在 30 秒的时候开始,每隔 10 秒钟 | second = "30,40,50" |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | @Stateless public class StatisticsEJB { @Schedule(dayOfMonth = "1", hour = "5", minute = "30") public void statisticsItemsSold() { // ... } @Schedules({ @Schedule(hour = "2"), @Schedule(hour = "14", dayOfWeek = "Wed") }) public void generateReport() { // ... } @Schedule(minute ="*/10", hour = "*", persistent = false) public void refreshCache() { // ... } } |
1 2 3 4 | new ScheduleExpression().dayOfMonth("Mon").month("Jan"); new ScheduleExpression().second("10,30,50").minute("*/5").hour("10-14"); new ScheduleExpression().dayOfWeek("1,5").timezone("Europe/Lisbon"); new ScheduleExpression().dayOfMonth(customer.getBirthDay()) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | @Stateless public class CustomerEJB { @Resource TimerService timerService; @PersistenceContext(unitName = "chapter07PU") private EntityManager em; public void createCustomer(Customer customer) { em.persist(customer); ScheduleExpression birthDay = new ScheduleExpression(). dayOfMonth(customer.getBirthDay()).month(customer.getBirthMonth()); timerService.createCalendarTimer(birthDay, new TimerConfig(customer, true)); } @Timeout public void sendBirthdayEmail(Timer timer) { Customer customer = (Customer) timer.getInfo(); // ... } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | @Singleton public class CacheEJB { private Map<long , object> cache = new HashMap<long , object>(); @PostConstruct private void initCache() { // Initializes the cache } public Object getFromCache(Long id) { if (cache.containsKey(id)) return cache.get(id); else return null; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | @Stateful public class ShoppingCartEJB { @Resource private DataSource ds; private Connection connection; private List<item> cartItems = new ArrayList<item>(); @PostConstruct @PostActivate private void init() { connection = ds.getConnection(); } @PreDestroy @PrePassivate private void close() { |
17 18 19 20 21 22 23 24 25 26 | connection.close(); } // ... @Remove public void checkout() { cartItems.clear(); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | @Stateless public class CustomerEJB { @PersistenceContext(unitName = "chapter08PU") private EntityManager em; private Logger logger = Logger.getLogger("com.apress.javaee6"); public void createCustomer(Customer customer) { em.persist(customer); } public Customer findCustomerById(Long id) { return em.find(Customer.class, id); } @AroundInvoke private Object logMethod(InvocationContext ic) throws Exception { logger.entering(ic.getTarget().toString(), ic.getMethod().getName()); try { return ic.proceed(); } finally { logger.exiting(ic.getTarget().toString(), ic.getMethod().getName()); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 | public class LoggingInterceptor { private Logger logger = Logger.getLogger("com.apress.javaee6"); @AroundInvoke public Object logMethod(InvocationContext ic) throws Exception { logger.entering(ic.getTarget().toString(), ic.getMethod().getName()); try { return ic.proceed(); } finally { logger.exiting(ic.getTarget().toString(), ic.getMethod().getName()); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | @Stateless public class CustomerEJB { @PersistenceContext(unitName = "chapter08PU") private EntityManager em; @Interceptors(LoggingInterceptor.class) public void createCustomer(Customer customer) { em.persist(customer); } public Customer findCustomerById(Long id) { return em.find(Customer.class, id); } } |
1 2 3 4 5 6 7 8 9 | @Stateless @Interceptors(LoggingInterceptor.class) public class CustomerEJB { public void createCustomer(Customer customer) { ... } public Customer findCustomerById(Long id) { ... } } |
1 2 3 4 5 6 7 8 9 10 11 | @Stateless @Interceptors(LoggingInterceptor.class) public class CustomerEJB { public void createCustomer(Customer customer) { ... } public Customer findCustomerById(Long id) { ... } public void removeCustomer(Customer customer) { ... } @ExcludeClassInterceptors public Customer updateCustomer(Customer customer) { ... } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | public class ProfileInterceptor { private Logger logger = Logger.getLogger("com.apress.javaee6"); @PostConstruct public void logMethod(InvocationContext ic) { logger.entering(ic.getTarget().toString(), ic.getMethod().getName()); try { return ic.proceed(); } finally { logger.exiting(ic.getTarget().toString(), ic.getMethod().getName()); } } @PreDestroy public void profile(InvocationContext ic) { long initTime = System.currentTimeMillis(); try { return ic.proceed(); } finally { long diffTime = System.currentTimeMillis() - initTime; logger.fine(ic.getMethod() + " took " + diffTime + " millis"); } } } |
1 2 3 4 5 6 7 | @Stateless @Interceptors(ProfileInterceptor.class) public class CustomerEJB { @PersistenceContext(unitName = "chapter08PU") private EntityManager em; @PostConstruct |
8 9 10 11 12 13 14 15 16 17 18 19 | public void init() { // ... } public void createCustomer(Customer customer) { em.persist(customer); } public Customer findCustomerById(Long id) { return em.find(Customer.class, id); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 | @Stateless @Interceptors(I1.class, I2.class) public class CustomerEJB { public void createCustomer(Customer customer) { ... } @Interceptors(I3.class, I4.class) public Customer findCustomerById(Long id) { ... } public void removeCustomer(Customer customer) { ... } @ExcludeClassInterceptors public Customer updateCustomer(Customer customer) { ... } } |
1 2 3 4 | <assembly-descriptor> <interceptor-binding> <ejb-name>*</ejb-name> <interceptor-class> |
5 6 7 8 | com.apress.javaee6.ProfileInterceptor </interceptor-class> </interceptor-binding> </assembly-descriptor> |
1 2 3 4 5 6 7 8 9 10 11 | @Stateless @ExcludeDefaultInterceptors @Interceptors(LoggingInterceptor.class) public class CustomerEJB { public void createCustomer(Customer customer) { ... } public Customer findCustomerById(Long id) { ... } public void removeCustomer(Customer customer) { ... } @ExcludeClassInterceptors public Customer updateCustomer(Customer customer) { ... } } |
1 2 3 4 5 6 | package greetings; public class Greeting { public String greet(String name) { return "Hello, " + name + "."; } } |
欢迎光临 飞网论坛 (https://bbs.cfei.net/) | Powered by Discuz! X3.2 |