1.http://stackoverflow.com/questions/25598406/spring-annotaion-autowired-inside-methods

Q:

Autowire can be used with constructors, setter and as class variables.

How can I used @Autowire annotation inside a method or any other scope.

A:

Even if it could, there's nothing Spring or any runtime environment could do about it because reflection doesn't provide any hooks into method bodies. You wouldn't be able to access that local variable at runtime.

You'll have to move that local variable to a field and autowire that.

2.http://stackoverflow.com/questions/10997092/autowiring-in-spring-bean-component-created-with-new-keyword

Q:

I have two spring beans as follows:

@Component("A")
@Scope("prototype")
public class A extends TimerTask { @Autowired
private CampaignDao campaignDao;
@Autowired
private CampaignManager campManger;
A(){
init_A();
}
}

I have to make a new object of A with new keyword, due to a legacy code

@Component("B")
@Scope("prototype")
public class B{
public void test(){
A a = new A();
}
}

when Running -> the spring beans in the class A are null, can i create a new instance of the spring bean A and still use autowiring in it ?

A:

Yours component "A" is not created by Spring container, thus, dependencies are not injected. However, if you need to support some legacy code (as I understand from your question), you can use@Configurable annotation and build/compile time weaving:

@Configurable(autowire = Autowire.BY_TYPE)
public class A extends TimerTask {
// (...)
}

Then, Spring will inject autowired dependencies to component A, no matter if it's instantiated by container itself, or if it's instantiated in some legacy code by new.

3.http://stackoverflow.com/questions/7201728/how-are-spring-handlerinterceptors-instantiated

Q:

Is there a new instance of Spring HandlerInterceptors for each request?

I have an interceptor in Spring, which has a class field.

public class MyInterceptor extends HandlerInterceptorAdapter {
Private boolean state = false; @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
state = true;
return true;
} @Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
if (state == true) {
System.out.println("Success");
}
}

If this interceptor is used will it always print "Success"? (No matter how many threads are doing this at the same time?)

A:

How the interceptor is instantiated depends how you configiure it as a bean. If you don't explicitly specify a scope for the bean, then it'll be a singleton like any other bean, and so the state field will be shared by all requests.

In this sense, interceptors are no different to controllers - be very careful about putting conversation state in them, since the objects will be shared across requests.

if you really need a stateful interceptor and you don't want to share the state between requests, then use a request-scoped bean.

4.http://stackoverflow.com/questions/26131603/autowire-of-prototype-bean-into-prototype-bean

Q:

@Scope("prototype")
public class MyPrototypeClass { @Autowired
private ReallyGoodSingletonService svc; @Autowired
private APrototypeBean bean; public void doSomething() {
bean.doAThing();
}
} @Scope("prototype)
public class APrototypeBean {
private int stuffgoeshere; public void doAThing() {
}
}

So when doSomething() in MyPrototypeClass is called, is that "bean" a singleton or a new one for each instance of MyPrototypeClass?

A:

In your example, the APrototypeBean bean will be set to a brand new bean which will live through until the instance of MyPrototypeClass that you created is destroyed.

If you create a second instance of MyPrototypeClass then that second instance will receive its own APrototypeBean. With your current configuration, every time you call doSomething(), the method will be invoked on an instance of APrototypeBean that is unique for that MyPrototypeClass object.

5.http://stackoverflow.com/questions/21827548/spring-get-current-applicationcontext

Q:

I am using Spring MVC for my web application. My beans are written in "spring-servlet.xml" file

Now I have a class MyClass and i want to access this class using spring bean

In the spring-servlet.xml i have written following

<bean id="myClass" class="com.lynas.MyClass" />

Now i need to access this using ApplicationContext

ApplicationContext context = ??

So that I can do

MyClass myClass = (MyClass) context.getBean("myClass");

How to do this??

A:

Simply inject it..

@Autowired
private ApplicationContext appContext;

or implement this interface: ApplicationContextAware

6.

Q:

public class UserBoImpl implements UserBo{

@Autowired
UserDao userDao;

public void syso() {
userDao.save();
}

}
这应该是最普遍的Spring注入模版  
userDao是何时被实例化的??? 
是调用save方法时  还是 Spring IOC容器建立时 ????
Spring又是如何处理Autowire这个注释的??何时处理的???

A:

默认情况下,bean的装配顺序是
new实例化 -> PostConstruction -> Autowire
至于你这个dao何时实例化,要看你是怎么声明的scope
默认是单例,也就是spring被加载时实例化
如果是scope("prototype")那就是这个dao被引用的时候进行实例化.

[注]如果UserBoImpl也是prototype类型,那么userDao会在程序生成UserBoImpl(例如调用getbean)的时候完成初始化,如果UserBoImpl是singleton类型,那么userDao也会因为UserBoImpl在spring启动的时候初始化而一道被注入。严格意义上来说,外层对象Out声明为singleton,内层成员变量Inner声明为prototype,外层对象中所有的成员函数out.func()和成员变量out.mem都将共享这个Inner。Inner变量只会在Out对象初始化时一起被初始化,有且仅有这一次。

7.http://stackoverflow.com/questions/13951733/contextannotation-config-and-contextcomponent-scan

Q:

In Spring 3 do I need to have <context:annotation-config> and <context:component-scan> defined in order to enable @PostConstruct?

A:

<context:annotation-config> is enough, after that you can instantiate your beans from context.xml and @PostConstruct, @Autowired, @Resource and some other annotations that Spring supports will be processed. Note if you use component-scan annotation-config mode is enabled by default.

8. http://stackoverflow.com/questions/7414794/difference-between-contextannotation-config-vs-contextcomponent-scan

Q:

I'm learning Spring 3 and I don't seem to grasp the functionality behind <context:annotation-config>and <context:component-scan>.

From what I've read they seem to handle different annotations (@Required, @Autowired etc vs @Component, @Repository, @Service etc) but also from what I've read they register the same bean post processor classes.

To confuse me even more, there is an annotation-config attribute on <context:component-scan>.

Can someone shed some light on these tags? What's similar, what's different, is one superseded by the other, they complete each other, do I need one of them, both?

A:

<context:annotation-config> is used to activate annotations in beans already registered in the application context (no matter if they were defined with XML or by package scanning).

<context:component-scan> can also do what <context:annotation-config> does but <context:component-scan> also scans packages to find and register beans within the application context.

9. http://stackoverflow.com/questions/18578143/about-multiple-containers-in-spring-framework/18580299#18580299

Q:

In a typical Spring MVC project there two "containers": One created by ContextLoaderListener and the other created by DispatchServlet.

I want to know, are these really two IoC container instance?( I see two bean config files, one is root-context.xml the other is servlet-context.xml)

If there are 2 containers, then what's the relationship?

Can the beans declared in one container be used in the other?

A:

After years later, I have read the spring source code. Now, I can say: 1) yes, there are two instance of ApplicationContext ( each instance will include a instance of beanFactory) 2) the instance of the mvc layer is child and keep a reference of the parent instance. 3) beans in parent instance can be used by child, but beans in child cannot be used by parent.

In Spring Web Applications, there are two types of container, each of which is configured and initialized differently. One is the “Application Context” and the other is the “Web Application Context”. Lets first talk about the “Application Context”. Application Context is the container initialized by a ContextLoaderListener or ContextLoaderServlet defined in the web.xml and the configuration would look something like this:

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:*-context.xml</param-value>
</context-param>

In the above configuration, I am asking spring to load all files from the classpath that match *-context.xml and create an Application Context from it. This context might, for instance, contain components such as middle-tier transactional services, data access objects, or other objects that you might want to use (and re-use) across the application. There will be one application context per application.

The other context is the “WebApplicationContext” which is the child context of the application context. Each DispatcherServlet defined in a Spring web application will have an associated WebApplicationContext. The initialization of the WebApplicationContext happens like this:

<servlet>
<servlet-name>platform-services</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:platform-services-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

You provide the name of the spring configuration file as a servlet initialization parameter. What is important to remember here is that the name of the XML must be of the form -servlet. xml. In this example, the name of the servlet is platform-services therefore the name of our XML must be platform-service-servlet.xml. Whatever beans are available in the ApplicationContext can be referred to from each WebApplicationContext. It is a best practice to keep a clear separation between middle-tier services such as business logic components and data access classes (that are typically defined in the ApplicationContext) and web- related components such as controllers and view resolvers (that are defined in the WebApplicationContext per Dispatcher Servlet).

Spring MVC坑汇总+Stackoverflow巧解答的更多相关文章

  1. spring mvc 坑之PUT,DELETE方法接收不到请求参数

    https://www.cnblogs.com/roobtyan/p/9576685.html 原因: Tomcat处理参数的问题: 1.将请求体中的数据,封装成一个map    2.request. ...

  2. Spring MVC+Hibernate JPA搭建的博客系统项目中所遇到的坑

    标签: springmvc hibernate 2016年12月21日 21:48:035133人阅读 评论(0) 收藏 举报  分类: Spring/Spring MVC(6)  Hibernate ...

  3. 好大滴坑, Spring MVC覆盖了Trsaction

    好大滴坑. Spring MVC覆盖了Trsaction 解决方式: <!-- package-scan 4 Spring MVC --> <context:component-sc ...

  4. Spring MVC & Boot & Cloud 技术教程汇总(长期更新)

    昨天我们发布了Java成神之路上的知识汇总,今天继续. Java成神之路技术整理(长期更新) 以下是Java技术栈微信公众号发布的关于 Spring/ Spring MVC/ Spring Boot/ ...

  5. spring mvc踩坑记

    前言 主要介绍自己在学习spring mvc过程中踩到的一些坑,涉及到当时遇到这个错误是如何思考的,对思路进行总结,下次遇到类似的错误能够提供一些思路甚至快速解决. 环境准备 jdk8,spring4 ...

  6. spring mvc mybatis集成踩的坑

    开园这么多年了也没写几篇文章,现在想想光看别人的也不行啊,咱也自己写写,就写这天我我在做spring mvc与mybatis的集成时遇到的问题 1 spring与mybatis的集成 这个相信大家都弄 ...

  7. java web轻量级开发面试教程摘录,java web面试技巧汇总,如何准备Spring MVC方面的面试

    本内容摘自 java web轻量级开发面试教程 https://baike.baidu.com/item/Java%20Web%E8%BD%BB%E9%87%8F%E7%BA%A7%E5%BC%80% ...

  8. 从content-type设置看Spring MVC处理header的一个坑

    我们经常需要在HttpResponse中设置一些headers,我们使用Spring MVC框架的时候我们如何给Response设置Header呢? Sooooooooooooo easy, 看下面的 ...

  9. 基于maven来Spring MVC的环境搭建遇到“坑”

    1.注解配置路径问题: 在web.xml中配置spring mvc 路径时, 应该配置如下:classpath:classpath:spring-* 2.jdk版本和Spring MVC版本不一致问题 ...

随机推荐

  1. 子查询在UPDATE 语句中的应用

    在UPDATE语句中可以在更新列表中以及WHERE语句使用子查询.下面演示一个将图书的出版日期全部更新为所有图书中的最新出版日期,SQL语句如下: UPDATE T_Book SET FYearPub ...

  2. 连接LilyPad之Windows平台的驱动

    连接LilyPad之Windows平台的驱动 LilyPad和其他的Arduino控制板的不同之处是它是为电子织物和可穿戴设计的.那么,它的大小就必须要紧凑.所以,它并没有板载其他大多数板子都具有的U ...

  3. 「NOI2018」归程

    「NOI2018」归程 题目描述 本题的故事发生在魔力之都,在这里我们将为你介绍一些必要的设定. 魔力之都可以抽象成一个 >\(1\) 个节点. \(m\) 条边的无向连通图(节点的编号从 \( ...

  4. JZYZOJ1539[haoi2015]T2 树链剖分

    http://172.20.6.3/Problem_Show.asp?id=1539 在学校的OJ又写了一次,RE了好多次,原来haoi的时候这道题需要开栈+快读,裸数据结构30分,加上快读50分.o ...

  5. 【枚举】【最小表示法】XVII Open Cup named after E.V. Pankratiev Stage 14, Grand Prix of Tatarstan, Sunday, April 2, 2017 Problem F. Matrix Game

    给你一个n*m的字符矩阵,将横向(或纵向)全部裂开,然后以任意顺序首尾相接,然后再从中间任意位置切开,问你能构成的字典序最大的字符串. 以横向切开为例,纵向类似. 将所有横排从大到小排序,枚举最后切开 ...

  6. python3-开发进阶 heapq模块(如何查找最大或最小的N个元素)

    一.怎样从一个集合中获得最大或者最小的 N 个元素列表? heapq 模块有两个函数:nlargest() 和 nsmallest() 可以完美解决这个问题. import heapq nums = ...

  7. [CF843D]Dynamic Shortest Path

    [CF843D]Dynamic Shortest Path 题目大意: 给定一个带权有向图,包含\(n(n\le10^5)\)个点和\(m(m\le10^5)\)条边.共\(q(q\le2000)\) ...

  8. Codeforces Round #127 (Div. 1) A. Clear Symmetry 打表

    A. Clear Symmetry 题目连接: http://codeforces.com/contest/201/problem/A Description Consider some square ...

  9. ENVI裁剪

    一.basic tools-->resize data进行规则裁剪 虽然是进行图像重采样工具,但也可以用于简单快速的裁剪 1. 选中要裁剪的图像: 对话框下面选择spatial subset(构 ...

  10. ConCurrent并发包 - Lock详解(转)

    synchronized的缺陷   我们知道,可以利用synchronized关键字来实现共享资源的互斥访问.Java 5在java.util.concurrent.locks包下提供了另一种来实现线 ...