Sunteți pe pagina 1din 47

Spring 2.

5
Spring without XML

About Speaker
!Speaker @ JavaOne, NFJS, Devcon, Borcon !Sun Certified Java 2 Architect. !Instructor for VisiBroker for Java, OOAD, Rational Rose,

and Java Development. !JBoss Certified Developer

Agenda
!Industry Forces !Whats New Spring 2.0 Spring 2.5 !Spring Annotations !Reducing Spring XML !Spring Without XML!

Industry Forces

!Annotations
EJB 3.X

JSR-250 Common Annotations JSR-299 Web Beans


!Guice / SEAM

Spring Frustrations
!Autowiring
Qualifiers

!Long XML Files !Required Injections

Spring 2.5 Whats New

Spring 2.0
!New Bean Scopes httpSession !Easier XML Configuration

<jee:jndi-lookup id="dataSource" jndi-name="jdbc/ MyDataSource"/>


!Task Execution framework !Portlet MVC !Dynamic Language Support Groovy JRuby !Message-driven POJOs !AOP Enhancements Includes @Aspect !JMX Annotation Support

Spring 2.0 Benefits


!Easier XML !Easier AOP !Movement toward

Annotations and Java 5 Support

Spring 2.5 Whats New


!More Reduction of XML

<context:* /> <jms:* />


!Significant Annotation Support

JSR 250 - @PostConstruct, @Resource JAX-WS 2.0s - @WebServiceRef EJB 3.0 - @EJB MVC annotations - @RequestParam, @RequestMapping Test Enhancements - Junit 4.4 and TestNG Stereotypes - @Component, @Controller Spring enhancements - @Autowired, AOP - @Configurable

Spring 2.5 Whats New (Cont.)


!AOP Point Cut

Bean Point Cut AspectJ load-time weaving **


!Auto-Detection of Components on Classpath

In combination with Annotations


!OpenJPA 1.0 support with SavePoints !Web Standards Updates

Tiles 2 JSF 1.2


!Autowiring of JRuby !JMX Configuration Enhancements

<context:mbean-export />

Spring 2.5 Notes


!Removed from Spring

JDK 1.3 Support Hibernate 2.1 and 3.0 Support (Must be Hibernate 3.1+) IBATIS SQL Maps 1.3 Apache OJB JDO 1.0 Support

!Jar Changes Spring-webmvc.jar and spring-webmvc-portlet.jar

MVC must use these jars for DispatcherServlet


No longer in spring.jar

!WebSphere and BEA Support JTA Detection

Biggest Spring 2.5 Benefits


!Easier Configuration Easier XML Auto-detection Annotations Fine Grain Autowiring !Amazing AOP Support

Spring Annotations

Spring Annotations
!Spring 2.x Data Access

Annotations !Spring 2.x Aspects !Spring 2.5 Context Annotations !Spring 2.5 Stereotypes !Spring 2.5 Factory Annotations !JSR-250 javax.annotations
!Spring 2.5 MVC Annotations

Spring 2.x Data Access Annotations


!@Transactional

Provides annotation driven demarcation for transactions


!@Repository

Indicates that a class functions as a repository or a data access object (DAO) Exceptions are transparently translated Springs DataAccessException Hierarchy

Spring 2.x Aspects


@Aspect public class TraceLogger { private static final Logger LOG = Logger.getLogger(TraceLogger.class); @Pointcut("execution(* com.cmentor.*Service(..))") public void serviceInvocation() { } @Before(" serviceInvocation()") public void log(JoinPoint joinPoint) { LOG.info("Before calling " + joinPoint.getSignature().getName() + " with argument " + joinPoint.getArgs()[0]); } }
!Requires:

<aop:aspectj-autoproxy />

Spring 2.5 New PointCut


!New 2.5 Pointcut Designator

Bean For Spring only (not AspectJ)

@Pointcut(bean(nameofBean*))
!Allows for stack selection

accountController -> accountService -> accountDAO @Pointcut(bean(account*)) matches vertical stack @Pointcut(bean(*DAO)) matches horizontal (all DAOs)

Spring 2.5 Context Annotations


!@Scope

Indicates the scope to use for annotated class instances Default == singleton Options:

Singleton Prototype Request Session Global session

Web Options:

Spring 2.5 Stereotypes


!@Component **

Indicates that a class is a component Class is a candidate for auto-detection Custom component extensions
!@Controller

Specialized Component Typically used with RequestMapping annotation Discussed in section on web mvc
!@Repository

2.0 stereotype previously mentioned Now an extension of @Component


!@Service

Intended to be a business service facade

Spring 2.5 Factory Annotations


!@Autowired Marks a constructor, field, setter or config method for injection. Fields are injected After construction Before config methods
@Autowired(required=false)

Config:

AutowiredAnnotationBeanPostProcessor !@Configurable

Marks class as being eligible for Spring-driven configuration Used with AspectJ !@Qualifier Qualifies a bean for autowiring May be customized !@Required Marks a method as being injection required

@Autowired Notes Spring 2.5


!Spring resources can be injected !No Loaders or *LoaderAware

@Autowired Private ApplicationContext appContext;

Configuring Autowired
<bean class=AutowiredAnnotationBeanPostProcessor / >
!Or

<context:annotation-config/>

Let me Qualify that


@Autowired @Qualifier(dataSourceName) Private DataSource dataSource
!Or

@Autowired public void init(@Qualifier(srcName) DataSource dataSource, Object2 obj) {}

DEMO

Spring 2.5 JSR-250 Support


!JSR-250 javax.annotations Requires

CommonAnnotationBeanPostProcessor bean or <context:annotation-config /> Injects a named resource


Spring name not JNDI Unless configured :) to use JNDI

@Resource

@PostConstruct

Method invocated after construction No XML Multiple methods possible Method invocated when application context hosting object is closed

@PreDestroy

@Resource Options
@Resource(name=dataSourceName) Public void setDataSource(DataSource source) { @Resource private DataSource dataSource; // name = dataSource <bean class=org.springframework.context.annotations.Common AttributeBeanPostProcessor> <property name=alwaysUseJndiLookup value=true /> Or <jee:jndi-lookup id=dataSource jdni-name=java:comp/env/jdbc/peopleDS />

@Resource Notes
!No Spring managed resource for the default name

Injects object of type if there is only one

!Can be Turned Off

<bean class=CommonAnnotationBeanPostProcessor> <property name=fallbackToDefaultTypeMatch value=false /> </bean>

The Spring Debate


!@Resource

@Resource private DataSource dataSource;


Or
!@Autowired

@Autowired @Qualifier(dataSourceName) Private DataSource dataSource

DEMO

Spring 2.5 MVC Annotations


!@Controller

Stereotype used to Controller of MVC Scanned for RequestMappings


!@RequestMapping

Annotates a handler method for a request Very flexible


!@RequestParam

Annotates that a method parameter should be bound to a web request parameter


!SessionAttributes

Marks session attributes that a handler uses

@RequestMapping - Extreme Flexibility


!Parameters can be Request / response / session WebRequest InputStream OutputStream @RequestParam +++ !Return types

ModelAndView Object Model Object Map for exposing model View Object String which is a view name Void if method wrote the response content directly

Spring 2.5 Controller Example


@Controller public class ConfController { @Autowired private confDB confDB; @RequestMapping("/sessionList") public String showSessionList(ModelMap model) { model.addAttribute("sessions", this.confDB.getSessions()); return "sessionList"; } @RequestMapping("speakerImage") public void streamSpeakerImage(@RequestParam("name") String name, OutputStream outputStream) throws IOException { this.confDB.getSpeakerImage(name,outputStream); } @RequestMapping("/clearDatabase") public String clearDB() { this.confDB.clear();

Spring 2.5
Spring with LESS XML

Spring with LESS XML


!Annotations

Aspects Component Autowiring


!Name spaces XML !Auto Discovery

Less XML Namespace options


!Namespace options XML !Move some environment properties out of XML <context:property-placeholder location=classpath:jdbc.properties />

Scanning For Discovery


!XML Configure Scan

Disable default filters

No auto-detect of @Component, @Repository, etc.

Exclude or Include filters Default Behavior


AutowiredAnnotationBeanPostProcessor CommonAnnotationBeanPostProcessor

<context:component-scan base-package=com.cmentor >

Filter your Scan


!Filter Types

Annotation Assignable Regex Aspectj

!Example:
<context:component-scan base-package="org.example"> <context:include-filter type="regex" expression=".*Stub.*Repository"/> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/> </context:component-scan>

Spring 2.5
Spring with NO XML

Spring without XML


!Java Configuration !Groovy !Java Configuration II

Auto Discovery

Spring Configuration Points


!Spring at the core:

Java metadata
!Separate from the metadata parsing

Java Configuration
!http://www.springframework.org/javaconfig

@Configuration public class NoXMLConfig { @Bean public GreetingService greetingService() { GreetingServiceImpl service = new GreetingServiceImpl(); service.setMessageRepository(messageRepository()); return service; } @Bean public MessageRepository messageRepository() { StubMessageRepository repository = new StubMessageRepository(); repository.initialize(); return repository; } }

Java Config Options


!@Configuration(defaultAutowire= Autowire.BY_TYPE,

defaultLazy= Lazy.FALSE) !@Bean(scope=Scope.PROTOTYPE)

Java Auto-Discovery
GenericApplicationContext context = new GenericApplicationContext(); ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context); scanner.scan(com.cmentor"); context.refresh();

Java and XML


GenericApplicationContext context = new GenericApplicationContext(); ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context); scanner.scan(com.cmentor"); BeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions("classpath:dataSource.xml"); context.refresh();

XML and Java


<context:component-scan base-package=com.cmentor >

Summary

! Spring 2.5 Annotations ! Spring MVC ! Spring 2.x Reduces XML ! Spring 2.5 Provides Auto-discovery ! Reality Check:
Most configurations will have XML and will provide a combination of annotations and XML

Questions

! Please Fill Out Surveys

Ken.sipe@perficient.com

S-ar putea să vă placă și