Excluding filter in Spring


 

Excluding filter in Spring

In this tutorial you will learn about how to exclude specified component in spring framework.

In this tutorial you will learn about how to exclude specified component in spring framework.

Exclude-Filter in Spring

In this tutorial you will learn about how to exclude specified component, if you want spring to avoid detection and inclusion  into the spring container exclude those files with the @Service annotation

StudentDAO.java

package com.roseindia.student.dao;

import org.springframework.stereotype.Service;

@Service
public class StudentDAO {
	@Override
	public String toString() {
		return " Inside StudentDAO";
	}
}

StudentService .java

package com.roseindia.student.services;

import org.springframework.stereotype.Service;

import com.roseindia.student.dao.StudentDAO;

@Service
public class StudentService {

	StudentDAO studentDAO;

	@Override
	public String toString() {
		return "StudentService [studentDAO=" + studentDAO + "]";
	}
}

AppMain .java

package com.roseindia.common;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.roseindia.student.services.StudentService;

public class AppMain {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				new String[] { "context.xml" });
		StudentService stud = (StudentService) context
				.getBean("studentService");
		System.out.println(stud);
	}
}

context.xml

<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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">

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

    <context:include-filter type="regex"
      expression="com.roseindia.student.services.*Service.*" />

    <context:exclude-filter type="regex"
      expression="com.mkyong.customer.dao.*DAO.*" />

  </context:component-scan>

<!-- 
The same can be done through this code also  
  
  <context:component-scan base-package="com.roseindia" >
  <context:exclude-filter type="regex" 
                 expression="com.roseindia.student.dao.*DAO.*" />
     </context:component-scan> 
-->
  

</beans>

When you run this application it will display message as shown below:


StudentService [studentDAO=null]

Download this example code

Ads