spring 注解使用小结

本文详细介绍了Spring框架中依赖注入的多种实现方式,包括使用普通注解、组件扫描、AOP等技术进行配置,并探讨了@Autowired、@Resource等注解的具体应用。

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

1使用普通注解 添加

 <context:annotation-config />  

2使用@Component 添加 

 <context:component-scan base-package="com.bjsxt"/>  

  进行包扫描

3使用AOP添加

 <aop:aspectj-autoproxy />


<context:annotation-config/> 的作用【此次还有待验证,是否符合3.0特性】

<context:annotation-config/>

他的作用是隐式地向 Spring 容器注册

AutowiredAnnotationBeanPostProcessor、

CommonAnnotationBeanPostProcessor、

PersistenceAnnotationBeanPostProcessor、

RequiredAnnotationBeanPostProcessor 

5 @Repository , @Service , @Controller 和 @Component
四者几乎没有区别,根据名字来看 分别存储 dao/service/表现层/那层都可用

理论上虽如此,如果用spring mvc  在进行跳转中还是必须用 @Controller 这个的,不然会找不到 路径【已经过验证】


6 使用Servlet+spring 获取 项目上下文文档的的代码

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletContext context = request.getSession().getServletContext();
		ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
		Service service = (Service)ctx.getBean("service");
		service.service();
	}

7 使用注解@Resource的方法

  1)配置文件中添加一句  <context:annotation-config />

   2) 在service 配置文件少写了dao参数

   3) 在service类中不必写dao 的set/get方法

  

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc" 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/mvc  
		http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
		http://www.springframework.org/schema/context  
		http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	<!--<mvc:annotation-driven />   -->
	 <context:annotation-config />
	
		<bean id="dao" class="com.zj.Dao"></bean>
		<bean id="service" class="com.zj.Service">
		
		</bean>
	</beans>
	

8  如果想更精简代码呢,可以使用 @Component 加在类 dao和service上这同一级别的几个注解,在配置文件中加上一个扫描包 则可以减少dao 和service的bean配置,

   而且发现一个奇怪的问题 ,如果添加了 包扫描 ,可以去掉 

 <context:annotation-config /> 这句的配置了,虽然验证了一次,还是不太相信,先记录下来

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

静山晚风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值