Spring FAQ

来源:互联网 发布:南宁哪有美工勾刀卖 编辑:程序博客网 时间:2024/05/22 09:16

1. How to define a Spring bean using annotation instead of XML?

     Annotate the class with @Component, and in spring config file, add the package where your spring bean resides to component-scan package like this
   <context:component-scan base-package="com.test.**.service,com.test.aop.aspect" ></context:component-scan>

2. How to enable annotation-driven aspects in Spring?
Add < aop:aspectj-autoproxy /> to spring config file. 
<aop:aspectj-autoproxy/> will create an  AnnotationAwareAspectJAutoProxyCreator in the Spring context and will automatically proxy beans whose methods match the pointcuts defined with @Pointcut annotations in @Aspect-annotated beans.

3. How to specify that an advice is executed outside the transaction of the join point?
Specify the orders of the aspect and transaction. For aspect, annotation org.springframework.core.annotation.Order can be used. For transaction, order can be specified in spring config file. A greater value represents a lower priority.
     <tx:annotation-driven transaction-manager="transactionManager"  proxy-target-class="true" order="100"/>

@Order(1)
@Aspect
@Component
public class TestAspect
{
        @AfterReturning(pointcut = "execution(* com.test.service.GuestTypeSsidModificationService.handleGuestTypeModification(..))")
        public void rescanAndUpdatePpskGuests(JoinPoint joinPoint)
       {
              System. out.println("Outside join point transaction." );
       }
}

4. How to specify the which advice take precedence while two advices advise the same method?
Again, use org.springframework.core.annotation.Order and give them different values.

5. Are spring managed beans all singleton?
Not necessarily.
Various bean scopes can be specified with org.springframework.context.annotation.Scope.

singleton

Scopes a single bean definition to a single object instance per Spring IoC container.

prototype

Scopes a single bean definition to any number of object instances.

request

Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

session

Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

global session

Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.
For instance, annotate a class with @Scope ("prototype"), and each time bean of this type fetched is a new instance.
@Component
@Scope("prototype" )
public class JobStateCreateThread implements Callable<GuestTypeUpdJobState>
{
     ... ...
}

ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();
JobStateCreateThread jobStateCreateThread = applicationContext.getBean(JobStateCreateThread. class);//a new instance

6. How to get Spring context in a static way?
  Define util class like 

import
 org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ApplicationContextProvider implements ApplicationContextAware
{

        private ApplicationContextProvider()
       {
       }

        private static ApplicationContext  applicationContext   = null ;

        public static ApplicationContext getApplicationContext()
       {
               return applicationContext ;
       }

        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
       {
               ApplicationContextProvider. applicationContext = applicationContext;
       }

}

And declare bean in spring config file
<bean id= "applicationContextProvider"
               class= "com.test.core.common.ApplicationContextProvider" lazy-init="false" ></bean>

7. How to use batch operations of spring jdbc template?
     1. Bean extends org.springframework.jdbc.core.support.JdbcDaoSupport

@Service
public
class GuestBatchUpdateServiceImpl extends JdbcDaoSupport implements GuestBatchUpdateService
{
     ... ...
}
     2. Bean provides a constructor to set datasource
        @Autowired
        public GuestBatchUpdateServiceImpl(DataSource dataSource)
       {
              setDataSource( dataSource);
       }
     3. Define datasource in spring config file applicationContext.xml

     <bean id= "dataSource" class ="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close" >
        <property name= "driverClass" value ="${jdbc.driver}" />
        <property name= "jdbcUrl" value ="${jdbc.url}" />
        <property name= "user" value ="${jdbc.username}" />
        <property name= "password" value ="${jdbc.password}" />

        <property name= "minPoolSize" value ="${c3p0.minPoolSize}" />
        <property name= "maxPoolSize" value ="${c3p0.maxPoolSize}" />
        <property name= "initialPoolSize" value ="${c3p0.initialPoolSize}" />
        <property name= "maxIdleTime" value ="${c3p0.maxIdleTime}" />
        <property name= "acquireIncrement" value ="${c3p0.acquireIncrement}" />
        <property name= "idleConnectionTestPeriod" value="${c3p0.idleConnectionTestPeriod}" />
        <property name= "acquireRetryAttempts" value ="${c3p0.acquireRetryAttempts}" />
        <property name= "checkoutTimeout" value ="${c3p0.checkoutTimeout}" />
</bean>

          @Override
       public void updatePpskGuests(List<IdmGuest> guestList, String newSsid, int newUserProfileId)
       {
               int guestNum = guestList.size();
              String[] sqls = new String[guestNum];
               for (int i = 0; i < guestNum; i++)
              {
                     IdmGuest guest = guestList.get(i);
                     sqls[i] = "UPDATE idm_guest SET ssid='" + newSsid + "' WHERE id=" + guest.getId();
              }
               getJdbcTemplate().batchUpdate(sqls);
       }

0 0