(4)spring的annotation

本文详细解析了Spring框架中使用注解进行配置的方法,包括@Component、@Service、@Repository、@Controller等注解的使用场景,以及<context:annotation-config/>和<context:component-scan/>元素的作用。同时介绍了依赖注入的方式,如@Resource和@Autowired的区别,以及它们如何在类中自动装配Bean。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

beans.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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>
<context:component-scan base-package="spring"/>
</beans>

1.<context:annotation-config/>----打开spring的annotation

2.<context:component-scan base-package="spring"/>----设置从前缀为spring的包中找

 

@Component("UserAction")
//@Controller("UserAction")
@Scope("prototype")
public class UserAction {
	private User user;
	private int id;
	private UserService UserService;
	
	
	
public UserAction() {
	
	}

public UserAction(UserService userService) {
		this.UserService = userService;
	}


public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public UserService getUserService() {
		return UserService;
	}
@Resource
	public void setUserService(UserService userService) {
		this.UserService = userService;
	}

public void add() {
	UserService.add(user);
}

public void delete() {
	UserService.delete(id);
}

public void load() {
	UserService.delete(id);
}
}

@Component("userDao")相当于<bean id="userDao" class="spring.dao.UserDao">

@Scope("prototype")多例

@Resource() 自动完成依赖注入,默认通过byName(加在setXX前面)

@autoWired 默认通过类型(不建议使用,一个类有多个类型一样的属性就报错)

@Repository 一般用于dao的注入

@service 业务层,完成对service类的注入

@controller 控制层,完成对action类的注入

 

最佳实践;项目很大不建议使用annotation,项目很大,很多类,不会按照包分类,而是按照模块分,建议用xml

项目小的话用annotation还是很方便的。

### 如何在Spring框架中获取AnnotationMetadata 在Spring框架中,`AnnotationMetadata`接口用于描述类级别的元数据。这允许开发人员访问目标类型的注解信息而不必实例化该类型。对于基于Java配置或扫描组件的应用程序来说非常有用。 为了获得某个特定bean定义的`AnnotationMetadata`对象,可以利用`StandardReflectionMetadataReaderFactory`来读取并处理这些信息[^1]: ```java import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.core.type.filter.AnnotationTypeFilter; public class MetadataExample { private final MetadataReaderFactory metadataReaderFactory; public void readAnnotations(String className) throws IOException { MetadataReader reader = metadataReaderFactory.getMetadataReader(className); AnnotationMetadata annotationMetadata = reader.getAnnotationMetadata(); // 判断是否存在指定注解 boolean hasRestcontroller = annotationMetadata.hasAnnotation(RestController.class.getName()); System.out.println("Has RestController: " + hasRestcontroller); // 获取所有注解名称 Set<String> annotations = annotationMetadata.getAnnotationTypes(); for (String anno : annotations) { System.out.println(anno); } } } ``` 此外,在某些情况下可能需要通过实现自定义逻辑来间接取得此类信息。例如当使用AOP代理时,可以通过拦截器或者后处理器的方式捕获到被增强的目标对象及其关联的元数据[^4]。 如果是在编写测试案例或是工具性质的功能模块,则可以直接借助于反射API配合Spring提供的辅助方法来进行操作。比如下面这段代码展示了如何直接从已知class对象提取其上的注解详情: ```java import org.springframework.core.annotation.AnnotatedElementUtils; public static Map<String, Object> getClassLevelAnnotations(Class<?> clazz){ MultiValueMap<String, Object> attributes = AnnotatedElementUtils.getAllAnnotationAttributes(clazz, true, false); return CollectionUtils.isEmpty(attributes)? Collections.emptyMap():attributes.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().get(0))); } ``` 以上两种方式分别适用于不同场景下的需求,前者更侧重于编译期静态分析,后者则适合运行时期动态查询。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值