Spring strategy learning notes (1.14) -- Scanning components from classpath

Source: Internet
Author: User

Spring provides a powerful function ------- component scanning. It can automatically scan, detect, and instantiate your components from classpath by using the specific construction (stereotype) annotation (translated as a typical annotation in the book. Indicates that the basic annotation for a component managed by spring is@ Component. Other specific structural annotations include@ Repository,
@ Service and @ controller. They represent components in the persistence layer, service layer, and performance layer, respectively.
.

(1) do not automatically scan Components

Create entity class sequence:

public class Sequence {    private String id;    private String prefix;    private String suffix;        public Sequence() {            }    public Sequence(String id, String prefix, String suffix) {        this.id = id;        this.prefix = prefix;        this.suffix = suffix;    }    /**     * @return the id     */    public String getId() {        return id;    }    /**     * @param id     *            the id to set     */    public void setId(String id) {        this.id = id;    }    /**     * @return the prefix     */    public String getPrefix() {        return prefix;    }    /**     * @param prefix     *            the prefix to set     */    public void setPrefix(String prefix) {        this.prefix = prefix;    }    /**     * @return the suffix     */    public String getSuffix() {        return suffix;    }    /**     * @param suffix     *            the suffix to set     */    public void setSuffix(String suffix) {        this.suffix = suffix;    }}

Then, create an interface sequencedao for the Data Access Object (DAO ).

public interface SequenceDao {    public Sequence getSequence(String sequenceId);    public int getNextValue(String sequenceId);}

Implementation class sequencedaoimpl, no database used

public class SequenceDaoImpl implements SequenceDao {    private Map<String, Sequence> sequences;    private Map<String, Integer> values;    public SequenceDaoImpl() {        sequences = new HashMap<String, Sequence>();        sequences.put("IT", new Sequence("IT", "30", "A"));        values = new HashMap<String, Integer>();        values.put("IT", 100000);    }    public Sequence getSequence(String sequenceId) {        return sequences.get(sequenceId);    }    public synchronized int getNextValue(String sequenceId) {        int value = values.get(sequenceId);        values.put(sequenceId, value + 1);        return value;    }}

Create the sequenceservice service class to interact with Dao to process the sequence generation request

public class SequenceService {    private SequenceDao sequenceDao;    public void setSequenceDao(SequenceDao sequenceDao) {        this.sequenceDao = sequenceDao;    }    public String generate(String sequenceId) {        Sequence sequence = sequenceDao.getSequence(sequenceId);        int value = sequenceDao.getNextValue(sequenceId);        return sequence.getPrefix() + value + sequence.getSuffix();    }}

Bean configuration file

<?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:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">        <bean id="sequenceService" class="com.codeproject.jackie.springrecipesnote.springioc.SequenceService" autowire="byType">    <property name="sequenceDao" ref="sequenceDao" />    </bean>        <bean id="sequenceDao" class="com.codeproject.jackie.springrecipesnote.springioc.SequenceDaoImpl" /></beans>

Test sequencetest

public class SequenceTest {    @Test    public void testSequence() {        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");        SequenceService sequenceService = (SequenceService)applicationContext.getBean("sequenceService");        System.out.println(sequenceService.generate("IT"));        System.out.println(sequenceService.generate("IT"));    }}

(2) automatically scan Components
The component scanning function provided by spring2.5 can automatically scan, detect, and instantiate your components from classpath. By default, spring can detect all components with constructor annotations. It indicates that the basic annotation of a component managed by spring is @ component. It can be applied to the sequencedaoimpl class.

@Componentpublic class SequenceDaoImpl implements SequenceDao {  。。。。。。。。。。}

You can also apply this constructor annotation to the sequenceservice class so that spring can detect it. In addition, the @ autowired annotation can be applied to the sequencedao field to allow spring to automatically assemble according to the type.

@Componentpublic class SequenceService {    @Autowired    private SequenceDao sequenceDao;    public String generate(String sequenceId) {        Sequence sequence = sequenceDao.getSequence(sequenceId);        int value = sequenceDao.getNextValue(sequenceId);        return sequence.getPrefix() + value + sequence.getSuffix();    }}

With the constructor annotation applied to the component class, you canBy declaring an XML Element <context: component-scan>, let spring scan these annotations. In this element, you must specify a package for the scan component. The specified package and sub-package are scanned. You can use semicolons to separate multiple packages to be scanned. The preceding constructor annotation is sufficient for you to use beans.Spring writes the first letter of the class name in lower case, and uses the camper name Method for other parts to form the bean name.. The following code is valid:

SequenceService sequenceService = (SequenceService)applicationContext.getBean("sequenceService");

<Context: component-scan> An autowiredannotationbeanpostprocessor instance is also registered. This instance can automatically assemble attributes with @ autowired annotations.

<?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:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">    <context:component-scan base-package="com.codeproject.jackie.springrecipesnote.springioc" /></beans>

@ Component annotation is a basic constructor annotation used to represent general-purpose components. In fact, there are other specific constructor annotations used to represent components in different layers. @ Repository annotation indicates a DaO component in the persistence layer.

@Repositorypublic class SequenceDaoImpl implements SequenceDao {。。。。。。。。。。。。}

@ Service annotation indicates the service component in the service layer

@Repositorypublic class SequenceService {    @Autowired    private SequenceDao sequenceDao;。。。。。。。。。。。。。}

Another constructor annotation @ controller represents a controller component in the presentation layer.
(3) filter the components to be scanned

By default, spring will detect the User-Defined annotation types that are useful for @ component, @ repository, @ service, @ controller, or added with the @ component annotation. You can simply use a custom filter to modify and extend this behavior. Add them as sub-elements of the component-scan element include-filter or exclude-filter. Each filter element requires the type and expression attributes.
Spring3.x supports five filter types. The annotation and assignable types are used to specify the annotation type and class (or interface) for filtering ). The RegEx and aspectj types allow specifying Regular Expressions and aspectj entry-point expressions to match classes. The custom type must be customized.org.springframework.core.type .TypeFilterInterface. You can also disable the default filter by setting the use-default-filters attribute to false.

<?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:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"><context:component-scan base-package="com.codeproject.jackie.springrecipesnote.springioc" ><context:include-filter type="regex" expression="com\.codeproject\.jackie\.springrecipesnote\.springioc\..*Dao.*"/><context:include-filter type="regex" expression="com\.codeproject\.jackie\.springrecipesnote\.springioc\..*Service.*"/><context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan></beans>

Because you have applied the Include filter to detect all classes whose names contain Dao or service, the sequencedaoimpl and sequenceservice components can be automatically detected without constructor annotations.

public class SequenceDaoImpl implements SequenceDao {   。。。。。。}
public class SequenceService {    @Autowired    private SequenceDao sequenceDao;。。。。。。。。。。。。。。}

(4) component detected by naming
By default, spring changes the first character of a non-qualified class name to lowercase to name the detected component. For example, the sequenceservice class is named sequenceservice. You can specify the component name explicitly in the constructor annotation.

@Service("sequenceService")public class SequenceService {   。。。。。。}
@Repository("sequenceDao")public class SequenceDaoImpl implements SequenceDao {   。。。。。。}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.