Spring注解-(九)@Lookup的用法

本文最后更新于:June 14, 2022 pm

Spring 是目前主流的 Java Web 开发框架,是 Java 世界最为成功的框架。Spring框架是由于软件开发的复杂性而创建的。Spring使用的是基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅仅限于服务器端的开发。从简单性、可测试性和松耦合性角度而言,绝大部分Java应用都可以从Spring中受益。该框架是一个轻量级的开源框架,具有很高的凝聚力和吸引力。Spring 框架不局限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何 Java 应用都可以从 Spring 中受益。Spring 框架还是一个超级粘合平台,除了自己提供功能外,还提供粘合其他技术和框架的能力。

目录

在官方上被称为方法注入。注意要和前面的注入区别开,包括setter注入、构造方法注入都是给属性注入。

当一个类加上了abstract修饰,那么这个类就无法成为Bean,即使加了注解@Component。如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.SpringTestAnnotation.TestValue;

import org.springframework.stereotype.Component;

/**
* @Author DragonOne
* @Date 2022/6/10 11:16
* @墨水记忆 www.tothefor.com
*/
@Component
public abstract class Per {

public void show(){
System.out.println("Per show");
}

}

测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.SpringTestAnnotation;

import com.SpringTestAnnotation.TestValue.Per;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
* @Author DragonOne
* @Date 2022/6/10 11:16
* @墨水记忆 www.tothefor.com
*/
public class TestAnnotation {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(TestConfig.class);
Per per = applicationContext.getBean("per", Per.class);
per.show();
}
}

报错如下:

1
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'per' available

但是,可以通过注解@Lookup在抽象类中定义方法从而实现Bean的注入,如下:

目标类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.SpringTestAnnotation.TestValue;

import org.springframework.stereotype.Component;

/**
* @Author DragonOne
* @Date 2022/6/10 21:56
* @墨水记忆 www.tothefor.com
*/
@Component
public class OrderS {

}

使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.SpringTestAnnotation.TestValue;

import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.stereotype.Component;

/**
* @Author DragonOne
* @Date 2022/6/10 11:16
* @墨水记忆 www.tothefor.com
*/
@Component
public abstract class Per {

@Lookup("orderS") //通过Bean的名称注入
public OrderS show(){
return null;
}

}

其中,注解@Lookup中的值是已经存在的Bean的名称。

测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.SpringTestAnnotation;

import com.SpringTestAnnotation.TestValue.Per;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
* @Author DragonOne
* @Date 2022/6/10 11:16
* @墨水记忆 www.tothefor.com
*/
public class TestAnnotation {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(TestConfig.class);
Per per = applicationContext.getBean("per", Per.class);
System.out.println(per.show());
}
}

//输出
com.SpringTestAnnotation.TestValue.OrderS@4d826d77

可以看见,最后是成功返回了已经存在的Bean,而不是null值。这是为什么呢?

解释:通过注解@Lookup中的名称找到对应的Bean对象,然后直接作为方法的返回值。