注解

1. 注解方式IoC只是标记哪些类要被Spring管理
@Component
public class Xxx {
}
@Repository("dao")
public class XxxDao {
@Service
public class XxxService {
}
@Controller
public class XxxController {
}
2. 我们还需要XML方式或者Java配置类方式指定注解生效的
<?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 https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.wind.annotation"/>
</beans>
最后进行测试
点击查看代码
public class AnnotationTest {
@Test
public void test1() {
ClassPathXmlApplicationContext classPathXmlApplicationContext =
new ClassPathXmlApplicationContext("spring-annotation.xml");
XxxController bean = classPathXmlApplicationContext.getBean(XxxController.class);
System.out.println("+++++++@Controller+++++++");
System.out.println(bean);
Object xxxDao = classPathXmlApplicationContext.getBean("dao");
System.out.println("+++++++@Repository+++++++");
System.out.println(xxxDao);
XxxService xxxService = classPathXmlApplicationContext.getBean("xxxService", XxxService.class);
System.out.println("+++++++@Service+++++++");
System.out.println(xxxService);
}
}

组件的作用域和周期方法注解
@Component
@Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class Life {
@PostConstruct
public void init() {
System.out.println("初始化~~");
}
@PreDestroy
public void destroy() {
System.out.println("即将销毁~~~");
}
}
运行如下
@Test
public void test2() {
ClassPathXmlApplicationContext classPathXmlApplicationContext =
new ClassPathXmlApplicationContext("spring-annotation.xml");
Life life = classPathXmlApplicationContext.getBean(Life.class);
classPathXmlApplicationContext.close();
}

注解注意事项
private A c;
@Resource 先根据属性名去找 找不到再去根据类型去找
@Autowired 先根据类型去找 找不到再去根据属性名去找
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现