Bean 注解(Annotation)配置(1)- 通过注解加载Bean

Bean也可以通过Java注解的方式配置。

Java注解直接加在需要装配的Bean Java类上。

注解是类、方法或字段声明上的特殊标记。例如,常见的@Override就是一个注解,作用是告诉编译器这是一个被重写的方法。

注解配置对比XML配置

注解配置比XML配置更简洁,尤其是当有很多Bean时,可以省很多事。

XML注入会在注解注入之后执行,所以XML配置将覆盖注解配置。

1. 启用注解配置

默认情况下,Spring容器没有启用注解配置。需要在Bean的XML配置文件里打开组件扫描功能,启用注解配置。


<?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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 打开组件扫描,启用注解配置 --> <context:component-scan base-package="com.qikegu.demo"></context:component-scan> <!-- ... --> </beans>

base-package="com.qikegu.demo"指定需要扫描的包路径。

2. 给Bean Java类添加@Component注解

Spring容器扫描指定包路径下的所有类,每当找到1个@Component注解,就会注册Bean,同时设置Bean ID。

默认Bean ID就是类名,但首字母小写。如果类名以连续几个大写字母开头,首字母不小写。(即QIKEGUService -> QIKEGUService)


package com.qikegu.demo; import org.springframework.stereotype.Component; import org.springframework.context.annotation.Lazy; @Component @Lazy public class App { }

3. 通过Spring容器获取bean

与XML配置方式类似,使用getBean()方法返回Bean实例。

示例:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

        // 获取Bean实例
        App app = context.getBean("app", App.class);
        // App app = (App) context.getBean("app");
    }
}


浙ICP备17015664号-1 浙公网安备 33011002012336号 联系我们 网站地图  
@2019 qikegu.com 版权所有,禁止转载