Spring注解及用法(原始注解+新注解)

本文探讨了Spring框架中原始注解如@Component、@Controller、@Service、@Repository的使用,以及新注解如@Configuration、@Autowired、@Import等在替代XML配置中的作用。重点介绍了如何通过@Configuration类管理和扫描组件,以及如何使用@Bean动态创建Bean。

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

Spring原始注解:主要是替代的配置

@Component----------使用在类上用于实例化Bean(通用)

@Component(“UserServiceBean”)
<bean id="UserServiceBean" class="com.service.impl.UserServiceImpl"></bean>

@Controller------------使用在web层类用于实例化Bean

@Cotrollert(“UserControllerBean”)
<bean id="UserControllerBean" class="com.web.impl.UserControllerImpl"></bean>

@Service---------------使用在service层类用于实例化Bean

@Service(“UserControllerBean”)
<bean id="UserServiceBean" class="com.Service.impl.UseServiceImpl"></bean>

@Repository-----------使用在dao层类用于实例化Bean

@Repository(“UserDaoBean”)

@Autowired------------使用在字段上用于根据类型依赖注入(不建议使用)
@Qualifier--------------结合@Autowired一起使用,用于根据名称(id)进行依赖注入

@Autowired
@Qualifier(“UserDaoBean”)//按照id从容器中进行匹配

@Resource------------相当于@Autowired+@Qualifier,按照名称(id)进行注入(name=“id”)(推荐使用)

@Resource(name=“UserDaoBean”) //Resource也是通过id匹配

@Value------------------注入普通属性(和jstl结合)

@Value(“GuoDeGang”)
private String name;

@Scope----------------标注Bean的作用范围(单例或多个)

@Scope(“prototype”)或@Scope(“singleton”)

@PostConstruct------使用在方法上标注该方法是Bean的初始化方法(init-method)
@PostDestroy--------使用在方法上标注该方法是Bean的销毁方法(destroy-method)

Spring新注解:使用原始注解不能全部替代XML配置文件,还需要使用新注解进行配置替代,例如:

非自定义的Bean的配置:<bean>
加载properties文件的配置:<context:property-placeholder>
组件扫描的配置:<context:compponent-scan>
引入其他文件:<import>

@Configuration-----------用于指定当前类是一个Spring配置类,当创建容器时会从该类加载注解

@Configuration
public class SpringConfiguration {
}
代表核心配置类,管理其他子配置类。
创建ApplicationContext对象:
ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfiguration.class)

@Import-------------------用于导入其他配置类

@Import({Configuration_1.class,Configuration_2.class,…})
导入核心配置类需要的分配置类,可存储数组对象

@ComponentScan-------用于指定Spring在初始化容器时要扫描的包

@ComponentScan(“com.xxx”)
参数为basepackage

@Bean---------------------使用在方法上,标注将该方法的返回值存储到Spring容器中

@Bean(“dataSource”)
返回id=dataSource的Bean,同时可以获取当前方法中set()中的属性值作为properties

@PropertySource--------用于加载properties文件中的配置

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值