spring注解加载配置文件

本文深入解析Spring框架中配置类的使用方法,包括如何通过注解实现组件扫描、过滤及自定义bean的创建。同时,提供了具体的代码示例,如config.java配置类的编写和IOCTest.java测试类的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

配置类:congig.java 

package com.fsp.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Service;

import com.fsp.bean.Person;

//配置类 == 配置文件
@Configuration
/*@ComponentScan(value = "com.fsp",excludeFilters = {
		@Filter(type = FilterType.ANNOTATION,classes = {Controller.class,Service.class})
})*/
//excludeFilters = filter[] 指定扫描的时候按照什么规则排除那些组件
@ComponentScan(value = "com.fsp",includeFilters = {
		@Filter(type = FilterType.ANNOTATION,classes = {Service.class})
},useDefaultFilters = false)
//includeFilters = filter[] 指定扫描的时候按照什么规则包含哪些组件
//useDefaultFilters默认为true,必须改成false,不还是全部都加载
@ComponentScans(value = {
		@ComponentScan(value = "com.fsp",includeFilters = {
				@Filter(type = FilterType.ANNOTATION,classes = {Service.class})
		},useDefaultFilters = false)
})
//@ComponentScans可以配置多个@ComponentScan
public class MainConfig {

	@Bean
	public Person person() {
		return new Person("fsp",24);
	}
}

 测试类:IOCTest.java:

package com.fsp.test;

import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.fsp.config.MainConfig;

public class IOCTest {
	
	@Test
	public void test01() {
		AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
		String[] definitionNames = applicationContext.getBeanDefinitionNames();
		for (String name : definitionNames) {
			System.out.println(name);
		}
	}

}

导入包:

 <!-- spirng依赖核心容器 -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.12.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

 

源码分析

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员雪球

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值