展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

spring5入门(九):基于注解管理bean,创建对象

  • 注解简介
注解是代码特殊标记,格式:@注解名称(属性名称=属性值, 属性名称=属性值..)
使用注解,注解作用在类上面,方法上面,属性上面
使用注解目的:简化 xml 配置
  • 有关bean的注解
@Component
@Service
@Controller
@Repository
  • 使用注解创建对象

  • 添加依赖

  • 开启组件扫描

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.ychen"></context:component-scan>
</beans>

  • 创建bean,如果不指定value,默认时类名的首字母小写
@Component(value = "userService")
public class UserService {
public void add() {
System.out.println("service add.......");
}
}
  • 测试方法
public class Test3 {
@Test
public void testAdd() {
ApplicationContext context = new ClassPathXmlApplicationContext("bean7.xml");
UserService userService = context.getBean("userService", UserService.class);
System.out.println(userService);
userService.add();
}
}
  • 控制台
com.ychen.spring.ser.UserService@452e19ca
service add.......
Process finished with exit code 0
  • 组件扫描详情
<!-- 表示不扫描所有组件,只扫描带Controller注解的类 -->
<context:component-scan base-package="com.atguigu" use-defaultfilters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 表示除了带Controller注解的类都扫描 -->
<context:component-scan base-package="com.atguigu">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
posted @   DogLeftover  阅读(27)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示