
Spring
在Spring中,
XML<context:component-scan base-package="com.example"> <context:include-filter type="RegEx" expression="com.example.*Service"/></context:component-scan>在上面的示例中,只有类型为"com.example.*Service"的组件(例如UserService、OrderService)会被包含在Spring容器中,其他类型的组件将被排除。使用
XML<context:component-scan base-package="com.example"> <context:exclude-filter type="annotation" expression="org.Springframework.stereotype.Controller"/></context:component-scan>在上面的示例中,所有带有@Controller注解的组件将被排除在Spring容器之外,而其他类型的组件将被包含。案例代码为了更好地说明这个概念,我们来看一个实际的案例。假设我们有一个简单的Spring应用程序,其中包含了以下几个类:
Javapackage com.example;public interface Animal { void makeSound();}Javapackage com.example;import org.Springframework.stereotype.Component;@Componentpublic class Dog implements Animal { @Override public void makeSound() { System.out.println("Woof!"); }}Javapackage com.example;import org.Springframework.stereotype.Component;@Componentpublic class Cat implements Animal { @Override public void makeSound() { System.out.println("Meow!"); }}Javapackage com.example;import org.Springframework.context.annotation.AnnotationConfiGAPplicationContext;public class MAIn { public static void mAIn(String[] args) { AnnotationConfiGAPplicationContext context = new AnnotationConfiGAPplicationContext(); context.scan("com.example"); context.refresh(); Animal dog = context.getBean(Dog.class); dog.makeSound(); Animal cat = context.getBean(Cat.class); cat.makeSound(); context.close(); }}在上面的示例中,我们定义了一个Animal接口和两个实现了该接口的类:Dog和Cat。我们使用@Component注解将这两个类标记为Spring组件,并在MAIn类中使用了XML<context:component-scan base-package="com.example"> <context:include-filter type="assignable" expression="com.example.Dog"/></context:component-scan>这样修改后,只有Dog组件会被包含在Spring容器中,Cat组件将被排除在外。当我们运行MAIn类时,只会输出"Woof!"。排除Cat组件相反地,如果我们想排除Cat组件,可以使用
XML<context:component-scan base-package="com.example"> <context:exclude-filter type="assignable" expression="com.example.Cat"/></context:component-scan>这样修改后,只有Dog组件会被包含在Spring容器中,Cat组件将被排除在外。当我们运行MAIn类时,只会输出"Woof!"。通过使用
Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号