SSM框架中new对象问题

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/XiaHeShun/article/details/83818109

SSM框架中的对象管理问题


在controller层中,例如:

PersonController.java中有@Autoware PersonService personService;

在service层中,例如:

PersonService.java中有@Autoware PersonDao personDao;


问题:

在正常的PersonController.java中可以正常通过注解使用

但是:

如果是通过new PersonController()调用方法,在service层中是无法调用通过dao层的注解bean成功的。


原因:

在容器启动的时候,spring会去扫描注解,然后通过反射注入,把对象注入进去,所以在spring容器中的所以对象都是已经实例化好的了。所以,必须要去容器中取,才能取到注入好的对象。而通过new方式创建的对象,相当于创建了多一个对象的实例,所以通过@Resource的方式注入不了对象。


解决:

只能通过在xml中配置bean,然后通过加载xml配置文件,取到配置相应的bean(感觉很鸡肋的办法,可是又对框架没有办法)

SpringContextUtlis工具类(通过bean的名字来获取有效的bean

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;
@Service
public class SpringContextUtils implements ApplicationContextAware {
  
	public SpringContextUtils() {
		// TODO Auto-generated constructor stub
	}
	
    private static ApplicationContext applicationContext;
  
    public void setApplicationContext(ApplicationContext context) throws BeansException {
    applicationContext = context;
    }
  
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
  
    public static void createContext() {
    	applicationContext = new ClassPathXmlApplicationContext("spring-mvc.xml");
	}
    
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        if (applicationContext == null){
                    return null;
                }
        return (T)applicationContext.getBean(name); 
    }
}

在相应的spring-*.xml文件中手动写bean

 <!-- Service调用Dao -->
 <bean id="systemAction" class="com.cn.xt.system.SystemAction">
	<property name="systemMapper" ref="systemMapper"/>
</bean>

<!-- Dao调用sqlSessionFactory -->	
	<bean id="systemMapper" class="com.cn.xt.daoImpl.systemMapperImpl">
	<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

参考:

[1] https://blog.csdn.net/zou2ouzou/article/details/77683759

[2] https://blog.csdn.net/cyjdapao/article/details/79217110

猜你喜欢

转载自blog.csdn.net/XiaHeShun/article/details/83818109