自分で作ったり提供したりするものは、まず自分自身で使ってみろろということです。自分じゃ使わないものなら人はいくらでも無責任にも無思考にもなれる。そういう投げやりな「サービス」やら「プロダクツ」なんて、だれだってイヤだ。自分が作り手と同時に利用者の立場になれば、ちゃんと使えるレベルのものを提供しようとします。

2012年1月8日日曜日

Simple Spring Sample

testSpringBean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="cataction" class="com.test.CatAction">
  </bean>
</beans>

testClient
...
public static void setUpBeforeClass() throws Exception {
    BeanFactory factory = new ClassPathXmlApplicationContext(
            "testSpringBean.xml");
    CatAction catAction = factory.getBean("cataction", CatAction.class);

    System.out.println(catAction.SayHello("koma"));
}
...

CatAction.java
package com.test;
public class CatAction {
    public String SayHello(String name)
    {
        return "Helo " + name;
    }
}

WebApplicationContext
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app id="WebApp_ID">
  <display-name>testSpringWeb</display-name>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/testSpringBean.xml</param-value>
  </context-param>

  <listener>
    <listener-class>com.test.StartListener</listener-class>
  </listener>
</web-app>

StartListener.java
package com.test;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.ContextLoaderListener;

public class StartListener extends ContextLoaderListener {
    public StartListener() {
    }
    public void contextInitialized(ServletContextEvent event) {
        ServletContext servletContext = event.getServletContext();
        super.contextInitialized(event);
        WebApplicationContext webContext = (WebApplicationContext) servletContext
                .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        CatAction catAction = webContext.getBean("cataction", CatAction.class);
        System.out.println(catAction.SayHello("koma"));
    }
    public void contextDestroyed(ServletContextEvent event) {
    }
}

0 件のコメント:

コメントを投稿

ホームページ