基于 注解 方式 管理 Bean

注解

1. 注解方式IoC只是标记哪些类要被Spring管理

@Component
public class Xxx {
}

//@Repository(value = "dao")
@Repository("dao")
//当注解中只设置一个属性时,value属性的属性名可以省略
public class XxxDao {
    //默认情况:
    // 类名首字母小写就是 bean 的 id。例如:XxxController 类对应的 bean 的 id 就是 xxxController
    //也可

@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">
<!--    1.注解方式IoC只是标记哪些类要被Spring管理
我们还需要XML方式或者Java配置类方式指定注解生效的
-->
    <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_SINGLETON)  //默认单例
@Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE)  //多例  二选一
public class Life {
    //周期方法要求: 方法命名随意,但是要求方法必须是 public void 无形参列表
    @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  先根据类型去找 找不到再去根据属性名去找
posted @   微风抚秀发  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示