Spring

From no name for this wiki
Jump to: navigation, search

Spring 2.0 i.o.c.

Hello World für Spring inversion of control. Benötigte jars: spring.jar, commons-logging.jar.

Spring 2.0 für JDBC

Das Sample benötigt eine Derby Datenbank, welche mit dem JDK 1.6 von Sun mitgeliefert wird. Das jar befindet sich unter JDK_HOME/db/lib/derby.jar. Benötigte jars: spring.jar, commons-logging.jar, commons-jdbc.jar, commons-pool.jar

Spring 2.0 für JDBC mit Transaktionsmanagement

Basiert auf AspectJ. Benötigte jars: spring.jar, commons-logging.jar, commons-jdbc.jar, commons-pool.jar, aspectjrt.jar, aspectjweaver.jar


Spring 2.0 für JDBC mit TM über Anotationen

Benötigte jars: spring.jar, commons-logging.jar, commons-jdbc.jar, commons-pool.jar

WebapplicationContext

Wie kommt man zum WebApplicationContext? Dazu zuerst im web.xml einen Listener registrieren:

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
     classpath:applicationContext-business.xml
     /WEB-INF/applicationContext-security.xml
   </param-value>
</context-param>
 
 
<!--
  - Loads the root application context of this web app at startup.
  - The application context is then available via
  - WebApplicationContextUtils.getWebApplicationContext(servletContext).
  -->
   <listener>
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>

Im Java kann man wie folgt darauf zugreiffen:

  WebApplicationContext context = 
  WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());

Spring AOP

Beispiel Spring AOP ohne Annotationen

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany.app</groupId>
  <artifactId>springsample</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>springsample</name>
  <url>http://maven.apache.org</url>
  <dependencies>
 
 
   <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>2.5.6</version>
   </dependency>
 
   <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>2.5.6</version>
   </dependency>
 
   <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>2.5.6</version>
   </dependency>
 
 
   <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.14</version>
   </dependency>
 
 
   <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.4.2</version>
   </dependency>
 
 
 
   <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
   </dependency>
 
  </dependencies>
 
  <build>
 
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <!-- Replace src with source -->
          <src>1.5</src>
          <target>1.5</target>
          <debug/>
        </configuration>
      </plugin>
    </plugins>
 
  </build>
</project>


Das Spring Config File spring-config.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"      
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd                           
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
 
    <bean id="mybean" class="springaopsample.BeanImpl"/>
    <bean id="aoparound" class="springaopsample.AOPAround"/>
 
    <aop:config>
        <aop:pointcut id="pointcut1" expression="execution (* springaopsample.BeanImpl.*(..))"/>
        <aop:aspect id="aspect1" ref="aoparound">
            <aop:around method="doAround" pointcut-ref="pointcut1"/>
        </aop:aspect>
    </aop:config>
 
</beans>


Main.java


package springaopsample;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class Main {
 
    private static final Logger log = LoggerFactory.getLogger(springaopsample.Main.class);
 
    public static void main(String ... args){
        log.info("starting application");
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        Bean myBean = (Bean) context.getBean("mybean");
        myBean.action();
        myBean.action(4);
        log.info("done");
    }
 
}

AOPAround.java


package springaopsample;
 
import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
public class AOPAround {
 
    private static final Logger log = LoggerFactory.getLogger(AOPAround.class);
 
    public Object doAround(ProceedingJoinPoint pointcut) throws Throwable {
        Object result;
        log.info("around before");
        result = pointcut.proceed();
        log.info("around after");
        return result;
    }
 
}

Bean.java


package springaopsample;
 
 
public interface Bean {
 
    public void action();
 
    public int action(int i);
}

BeanImpl.java


package springaopsample;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
 
public class BeanImpl implements Bean {
 
    private static final Logger log = LoggerFactory.getLogger(springaopsample.BeanImpl.class);
 
    public void action() {
        log.info("action");
    }
 
    public int action(int i) {
        log.info("actin(int i)");
        return i;
    }
 
}


Beispiel Spring AOP mit Annotationen

Siehe auch Beispiel Spring AOP ohne Annotationen.

Das Spring Config File spring-config.xml

Hier <aop:aspectj-autoproxy/> einschalten, damit Annotationen gelesen werden.

<?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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd                           
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
 
    <aop:aspectj-autoproxy/>
    <bean id="mybean" class="springaopsample.BeanImpl"/>
    <bean id="aoparound" class="springaopsample.AOPAround"/>
 
 
</beans>



AOPAround.java


package springaopsample;
 
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
@Aspect
public class AOPAround {
 
    private static final Logger log = LoggerFactory.getLogger(AOPAround.class);
 
    @Around("execution (* springaopsample.BeanImpl.*(..))")
    public Object doAround(ProceedingJoinPoint pointcut) throws Throwable {
        Object result;
        log.info("around before");
        result = pointcut.proceed();
        log.info("around after");
        return result;
    }
 
}

Beispiel Spring als leichter Container

Spring als Ersatz für EJB:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>ch.testmaster</groupId>
  <artifactId>testmaster-spring-web</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>Testmaster as Spring</name>
  <url>http://maven.apache.org</url>
 
  <dependencies>
 
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.6</version>
      <scope>test</scope>
    </dependency>
 
    <dependency>
     <groupId>org.hibernate</groupId>
     <artifactId>hibernate-annotations</artifactId>
     <version>3.4.0.GA</version>
    </dependency>
 
    <dependency>
       <groupId>org.hibernate</groupId>
       <artifactId>hibernate-entitymanager</artifactId>
       <version>3.4.0.GA</version>
    </dependency>
 
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>ejb3-persistence</artifactId>
      <version>1.0.2.GA</version>
    </dependency>
 
    <dependency>
      <groupId>javax.faces</groupId>
      <artifactId>jsf-api</artifactId>
      <version>1.2</version>
    </dependency>
 
    <dependency>
      <groupId>javax.faces</groupId>
      <artifactId>jsf-impl</artifactId>
      <version>1.2_13</version>
    </dependency>
 
    <dependency>
      <groupId>org.apache.derby</groupId>
      <artifactId>derbyclient</artifactId>
      <version>10.4.2.0</version>
    </dependency>
 
 
    <dependency>
      <groupId>com.sun.facelets</groupId>
      <artifactId>jsf-facelets</artifactId>
      <version>1.1.10</version>
    </dependency>
 
 
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.1.2</version>
    </dependency>
 
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>
 
    <dependency>
      <groupId>javax.el</groupId>
      <artifactId>el-api</artifactId>
      <version>1.0</version>
      <scope>provided</scope>
    </dependency>
 
   <dependency>
      <groupId>com.sun.el</groupId>
      <artifactId>el-ri</artifactId>
      <version>1.0</version>
   </dependency>
 
   <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>2.5.6</version>
   </dependency>
 
   <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>2.5.6</version>
   </dependency>
 
   <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>2.5.6</version>
   </dependency>
 
   <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>2.5.6</version>
   </dependency>
 
   <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>2.5.6</version>
   </dependency>
 
   <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>2.5.6</version>
   </dependency>
 
   <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>2.5.6</version>
   </dependency>
 
  <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>2.5.6</version>
   </dependency>
 
  <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>2.5.6</version>
   </dependency>
 
  <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>2.5.6</version>
   </dependency>   
 
 
   <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.2.2</version>
   </dependency>
 
 
 
   <dependency>
      <groupId>icefaces</groupId>
      <artifactId>icefaces</artifactId>
      <version>1.8.1</version>
   </dependency>
 
   <dependency>
      <groupId>icefaces</groupId>
      <artifactId>icefaces-comps</artifactId>
      <version>1.8.1</version>
   </dependency>
 
   <dependency>
      <groupId>icefaces</groupId>
      <artifactId>icefaces-facelets</artifactId>
      <version>1.8.1</version>
   </dependency>
 
   <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.14</version>
   </dependency>
 
   <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>    
    <version>1.5.8</version>
   </dependency>
 
   <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.5.8</version>
   </dependency>
 
 
 
  </dependencies>
 
 
  <repositories>
      <repository>
            <id>maven-repository.dev.java.net</id>
            <name>Java Dev Net Repository</name>
            <url>http://download.java.net/maven/2/</url>
            <releases>
                  <enabled>true</enabled>
                  <updatePolicy>never</updatePolicy>
            </releases>
            <snapshots>
                  <enabled>true</enabled>
            </snapshots>
      </repository>
  </repositories>
 
 
  <build>
 
    <finalName>testmaster-web</finalName>
 
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.0.2</version>
        <configuration>
          <!-- replace src with source -->
          <src>1.5</src>
          <target>1.5</target>
          <debug/>
        </configuration>
      </plugin>
    </plugins>
 
  </build>
 
 
 <properties>
        <netbeans.hint.deploy.server>Tomcat60</netbeans.hint.deploy.server>
 </properties>
</project>

spring-config.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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
 
 
  <context:annotation-config/>
  <context:component-scan base-package="ch.testmaster.business"/>
 
 
  <bean id="myTxManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="myEmf"/>    
  </bean>
 
 
 
  <bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
   <property name="dataSource" ref="myDataSource"/>
   <property name="persistenceUnitName" value="TestMaster-PU"/>
   <property name="persistenceXmlLocation" value="classpath:persistence.xml"/>
  </bean>
 
 
  <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver"/>
    <property name="url" value="jdbc:derby://localhost:1527/testmaster"/>
    <property name="username" value="APP"/>
    <property name="password" value="APP"/>
  </bean> 
 
 
 
  <aop:config>
    <aop:pointcut id="productServiceMethods" expression="execution(* ch.testmaster.business.QuestionBCBean.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="productServiceMethods"/>
  </aop:config> 
 
  <tx:advice id="txAdvice" transaction-manager="myTxManager">
    <tx:attributes>
      <tx:method name="*" propagation="REQUIRES_NEW"/>
    </tx:attributes>
  </tx:advice> 
 
  <bean id="question-bc" class="ch.testmaster.business.QuestionBCBean"/>
 
 
</beans>


QuestionBCBean.java. Dieses Bean wurde von einem EJBean zu einen SpringBean umgewandelt. Lediglich die Annotation @Stateless musste man mit @Repository austauschen.


package ch.testmaster.business;
 
import ch.testmaster.entities.Question;
import ch.testmaster.entities.QuestionOption;
import ch.testmaster.entities.Text;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
 
/**
 *
 * @author Claude Glauser
 */
@Repository
public class QuestionBCBean implements QuestionBCLocal {
 
    private static final Logger log = LoggerFactory.getLogger(QuestionBCBean.class);
 
    @PersistenceContext
    protected EntityManager em;
 
    public Long createQuestion(QuestionParam q){
        log.debug("Creating a new question");
 
        Question question = new Question();
 
        //Questiontitle
        question.setTitle(q.getTitle());
 
        //QuestionText
        Text questionText = new Text();
        questionText.setText(q.getText());
        question.setQuestionText(questionText);
        log.debug("Text der Frage: {}", question.getQuestionText().getText());
 
        //Explanation
        Text explanationText = new Text();
        explanationText.setText(q.getExplanation());
        question.setExplanationText(explanationText);
 
        for(QuestionOptionParam o : q.getOptions()){
            QuestionOption option = new QuestionOption();
            option.setIsCorrect(o.getIsCorrect());
            Text optionText = new Text();
            optionText.setText(o.getTxt());
            option.setOptionText(optionText);
            option.setQuestion(question);
            question.getOptions().add(option);
        }
 
        em.persist(question);
        log.debug("Question persistet. id: {}", question.getId());
 
        return question.getId();
    }
 
 
    public void updateQuestion(QuestionParam q){
 
        log.info("Updating question with id {}", q.getId());
 
        if(q.getId() == null || q.getId() == 0){
            throw new BusinessException("Id der Frage darf bei Update nicht null sein!");
        }        
    }
 
}
 


 

Resourcen