spring servlet之注入bean对象

本文介绍如何在SpringMVC环境中自动注入Bean对象,通过使用Spring 3.1版本及@Autowired注解实现对业务类对象LoginService的自动装配。演示了从配置文件到Controller的具体实现过程。

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

spring mvc之注入bean对象
说明:
1.环境 :spring3.1
2.研究范围:spring mvc之自动注入bean对象。  spring ioc容器是对象容器,是java bean对象容器,是一个管理虚拟机内存的容器。开发人员可以把自己的业务对象放在IOC容器中,
让IOC容器管理内存,防止内存泄露。笔者经验:IOC容器一般用来管理我们的业务类对象,其他的非业务对象不适合放在容器中管理,防止并发数据异常。
还有IOC管理业务类对象,只要我们的业务类对象销毁,业务类对象所开辟的内存空间将被释放,无论在使用中我们的业务类对象开辟了多大的内存空间。

3.applicationContext.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:aop="http://www.springframework.org/schema/aop"
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.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
  
 <context:annotation-config /> <!--必须加入这句话 spring容器才能自动注入-->
 
 <bean id="loginService" class="com.service.LoginService" />
</beans>
4.spring servlet  <!--自动注入生效@Component -->

package com.servlet;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.service.LoginService;
import com.service.LogoutService;
import com.util.Constants;
@Component
@Controller
public class LoginServlet {
  @Autowired
  private LoginService  loginservice ;
     
 @RequestMapping(value="login")
 public  void  login(HttpServletRequest request,HttpServletResponse response) throws IOException{
  loginservice.login();
 
 }
}

5.bean 类
package com.service;


 

 

public class LoginService {
 
 
 public LoginService(){
  System.out.println("执行LoginService 构造函数");
 }
 
 public  void  login(){
  System.out.println("执行LoginService loign");
  
 }

 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

半部论语

如果觉得有帮助,打赏鼓励一下

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

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

打赏作者

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

抵扣说明:

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

余额充值