Spring(十三)- Spring 配置类的注解

一、Spring 配置类的注解

@Component等注解替代了< bean>标签,但是像< import>、< context:componentScan> 等非< bean> 标签怎样去使用注解替代呢?

<!-- 加载properties文件 --> 
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 组件扫描 --> 
<context:component-scan base-package="com.itheima"/>
<!-- 引入其他xml文件 --> 
<import resource="classpath:beans.xml"/>

1. @Configuration

定义一个配置类替代原有的xml配置文件,< bean>标签以外的标签,一般都是在配置类上使用注解完成的

@Configuration注解标识的类为配置类,替代原有xml配置文件,该注解第一个作用是标识该类是一个配置类,第二个作用是具备@Component作用

@Configuration
public class ApplicationContextConfig {}

2. @ComponentScan

@ComponentScan 组件扫描配置,替代原有xml文件中的< context:component-scan base-package=“”/>

@Configuration
@ComponentScan(basePackages = {"com.itheima.service", "com.itheima.dao"})
public class ApplicationContextConfig {}

base-package的配置方式:
⚫ 指定一个或多个包名:扫描指定包及其子包下使用注解的类
⚫ 不配置包名:扫描当前@componentScan注解配置类所在包及其子包下的类

3. @PropertySource

@PropertySource 注解用于加载外部properties资源配置,替代原有xml中的 < context:property-placeholder location=" "/> 配置

@Configuration
@ComponentScan
@PropertySource({"classpath:jdbc.properties","classpath:xxx.properties"})
public class ApplicationContextConfig {}

4. @Import

@Import 用于加载其他配置类,替代原有xml中的< import resource=“classpath:beans.xml”/>配置

@Configuration
@ComponentScan
@PropertySource("classpath:jdbc.properties")
@Import(OtherConfig.class)
public class ApplicationContextConfig {}
// 其他配置类,在主配置类中通过@Import被注入
public class OtherConfig{}

二、Spring 配置其他注解

1. @Primary

扩展:@Primary注解用于标注相同类型的Bean优先被使用权,@Primary 是Spring3.0引入的,与@Component
和@Bean一起使用,标注该Bean的优先级更高,则再通过类型获取Bean或通过@Autowired根据类型进行注入时,会选用优先级更高的

@Primary配合自定义bean使用

@Repository("userDao")
public class UserDaoImpl implements UserDao{}

@Repository("userDao2")
@Primary
public class UserDaoImpl2 implements UserDao{}

@Primary配合非自定义bean使用

@Bean
public UserDao userDao01() {
	return new UserDaoImpl();
}

@Bean
@Primary
public UserDao userDao02() { 
	return new UserDaoImpl2();
}

2. @Profile

扩展:@Profile 注解的作用是进行环境切换

<beans profile="test">

注解 @Profile 标注在类或方法上,标注当前产生的Bean从属于哪个环境,只有激活了当前环境,被标注的Bean才能被注册到Spring容器里,不指定环境的Bean,任何环境下都能注册到Spring容器里

@Repository("userDao")
@Profile("test")
public class UserDaoImpl implements UserDao{}

@Repository("userDao2")
public class UserDaoImpl2 implements UserDao{}

可以使用以下两种方式指定被激活的环境:
⚫ 使用命令行动态参数,虚拟机参数位置加载 -Dspring.profiles.active=test
⚫ 使用代码的方式设置环境变量 System.setProperty(“spring.profiles.active”, “test”);

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值