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");
}
}