| 注解是代码特殊标记,格式:@注解名称(属性名称=属性值, 属性名称=属性值..) |
| 使用注解,注解作用在类上面,方法上面,属性上面 |
| 使用注解目的:简化 xml 配置 |
| @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 |
| |
| <context:component-scan base-package="com.atguigu" use-defaultfilters="false"> |
| <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> |
| </context:component-scan> |
| |
| |
| <context:component-scan base-package="com.atguigu"> |
| <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> |
| </context:component-scan> |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!