Spring Core

What is compound or nested property name in Spring ?

You can use compound or nested property names when you set bean properties, as long as all components of the path except the final property name are not null.

For more information please read https://roytuts.com/compound-property-names-in-spring/

What is depends-on in Spring ?

When a bean is typically dependent on another bean then we specify the dependent bean using <ref/> element in XML-based configuration metadata. However, sometimes dependencies between beans are less direct; for example, a static initializer that initializes something like loading of database driver in a class needs to be triggered first. The depends-on attribute can explicitly force one or more beans to be initialized before the bean using this element is initialized.

The following example uses the depends-on attribute to express a dependency on a single bean:

<bean id="beanA" class="com.roytuts.BeanA" depends-on="beanB"/>
<bean id="beanB" class="com.roytuts.BeanB" />

The following example uses the depends-on attribute to express a dependency on multiple beans:

<bean id="beanA" class="com.roytuts.BeanA" depends-on="beanB, beanC">
    <property name="beanB" ref="beanB" />
</bean>
<bean id="beanB" class="com.roytuts.BeanB" />
<bean id="beanC" class="com.roytuts.BeanC" />

For more information please read https://roytuts.com/depends-on-in-spring/

What is lazy-initialized bean in Spring ?

By default ApplicationContext implementations create and configure all singleton beans as a part of the initialization process. Therefore, errors (if any) are discovered immediately in configuration or surrounding environments. When you do not want the pre-initialization of your singleton beans then you can prevent by making the bean definition as lazy-initialized. A lazy-initialized bean tells the IoC container to create a
bean instance when it is first requested, rather than at start-up.

In XML configuration metadata, this behavior is controlled by the lazy-init attribute on the <bean/> element; for example:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean name="exampleBean" class="com.roytuts.ExampleClass" lazy-init="true">
        <property name="email" value="contact@roytuts.com"/>
    </bean>
</beans>

When is lazy-initialized bean created at start-up in Spring ?

When a lazy-initialized bean is a dependency of a singleton bean then it is not actually lazy-initialized; hence the
ApplicationContext creates the lazy-initialized bean at start-up, because it must satisfy the singleton’s dependencies.

How to do lazy-initialized all beans in container level in Spring ?

Using default-lazy-init=”true” attribute in <beans/> element. For example,

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd" default-lazy-init="true">
    <bean name="bean1" class="...">
        ...
    </bean>
    <bean name="bean2" class="...">
        ...
    </bean>
    <bean name="bean3" class="...">
        ...
    </bean>
</beans>

What is autowire in Spring ?

The Spring container can autowire relationships between collaborating beans. You can allow Spring to resolve collaborators (other beans) automatically for your bean by inspecting the contents of the ApplicationContext.
In XML-based configuration metadata, you can specify autowire mode for a bean definition using the autowire attribute of the <bean/> element.

Advantages of autowire

Autowiring can significantly reduce the need to specify properties or constructor arguments.

Autowiring can update a configuration as your objects evolve. For example, if you need to add a dependency to a class, that dependency can be satisfied automatically without you needing to modify the configuration.

What are the autowire modes available in Spring ?

no

It is a default mode and no autowiring happens. Bean references must be defined via a ref element.

byName

Autowiring happens by property name. Spring looks for a bean with the same name as the property that needs to be autowired.

byType

Allows a property to be autowired if exactly one bean of the property type exists in the container. If more than one bean exists, a fatal exception is thrown, which indicates that you may not use byType autowiring for that bean. If there are no matching beans, nothing happens; the property is not set.

constructor

Analogous to byType, but applies to constructor arguments.

Limitations and disadvantages of autowiring in Spring ?

Autowiring works best when it is used consistently across a project otherwise it might be confusing to developers if it is used only in one or two beans.

Explicit dependencies in property and constructor-arg settings always override autowiring. You cannot apply autowire on primitives, Strings and Classes.

Autowiring is less exact than explicit wiring. Spring is careful to avoid guessing in case of ambiguity that might have unexpected results.

Wiring information may not be available to tools that may generate documentation from a Spring container.

Multiple bean definitions within the container may match the type specified by the setter method or constructor argument to be autowired. For arrays, collections, or Maps, this is not necessarily a problem. However for dependencies that expect a single value, this ambiguity is not arbitrarily resolved. If no unique bean definition is available, an exception is thrown.

How to exclude beans from autowiring in Spring ?

You can exclude a bean from autowiring by setting attribute autowire-candidate=”false” in the <bean/> element in XML configuration.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean name="bean" class="..." autowire-candidate="false">
        ...
    </bean>
</beans>

You can also limit autowire candidates based on pattern-matching against bean names by using one or more patterns within its default-autowire-candidates attribute in <beans/> element.

For example, to limit autowire candidate status to any bean whose name ends with Service, provide a value of *Service.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd" default-autowire-candidates="*Service">
    <bean name="restService" class="com.roytuts.spring.service.RestService">
        ...
    </bean>
    <bean name="statusService" class="com.roytuts.spring.service.StatusService">
        ...
    </bean>
    <bean name="jobService" class="com.roytuts.spring.service.JobService">
        ...
    </bean>
</beans>

To limit autowire candidate status on multiple patterns, define them in a comma-separated list. An explicit value of true or false for a bean definition’s autowire-candidate attribute always takes precedence, and for such beans, the pattern matching rules do not apply.

These techniques are useful for beans that you never want to be injected into other beans by autowiring. It does not mean that an excluded bean cannot itself be configured using autowiring. Rather, the bean itself is not a candidate for autowiring other beans.

What is c-namespace in Spring ?

Similar to p-namespace, c-namespace was introduced in Spring 3.1. It allows usage of inlined attributes for configuring the constructor arguments rather then nested constructor-arg elements.

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    <!-- below one line is for c-namespace -->
    xmlns:c="http://www.springframework.org/schema/c"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="beanA" class="com.roytuts.BeanA"/>
    <bean id="beanB" class="com.roytuts.BeanB"/>
    <!-- standard declaration -->
    <bean id="beanOther" class="com.roytuts.BeanOther">
        <constructor-arg ref="beanA"/>
        <constructor-arg ref="beanB"/>
        <constructor-arg value="Hello"/>
    </bean>
    <!-- c-namespace declaration -->
    <bean id="beanOther" class="com.roytuts.BeanOther" c:beanA-ref="beanA" c:beanB-ref="beanB" c:message="Hello"/>
</beans>

The c: namespace uses trailing -ref for bean references for setting the constructor arguments by their names.

For the rare cases where the constructor argument names are not available, you can use fallback to the argument indexes:

<!-- c-namespace index declaration -->
<bean id="beanOther" class="com.roytuts.BeanOther" c:0-ref="beanA" c:1-ref="beanB" c:2="Hello"/>

What is method injection in Spring ? When do you need method injection in Spring ?

Most of the beans are singleton in the container but sometimes we have a situation like – suppose singleton bean A needs to use non-singleton (prototype) bean B, perhaps on each method invocation on A. The container only creates the singleton bean A once, and thus only gets one opportunity to set the properties. The container cannot provide bean A with a new instance of bean B every time one is needed.

A solution is to forego some inversion of control. You can make bean A aware of the container by implementing the ApplicationContextAware interface, and by making a getBean(“B”) call to the container ask for (a typically new) bean B instance every time bean A needs it.

Suppose you want the singleton-scoped bean to acquire a new instance of the prototype-scoped bean repeatedly at runtime. You cannot dependency-inject a prototype-scoped bean into your singleton bean, because that injection occurs only once, when the Spring container is instantiating the singleton bean and resolving and injecting its dependencies. If you need a new instance of a prototype bean at runtime more than once then we need method injection.

What scopes are available for a bean in Spring ?

Singleton

It is a default scope. A single bean definition to a single object instance per Spring IoC container.

Prototype

A single bean definition to any number of object instances.

Request

A single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created from a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

Session

A single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring applicationContext.

Global Session

A single bean definition to the lifecycle of a global HTTP Session. Typically only valid in a portlet context and a web-aware Spring ApplicationContext.

Application

A single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.

What is the difference between Spring AOP and AspectJ AOP?

AspectJ is the industry-standard implementation for Aspect Oriented Programming whereas Spring implements AOP for some cases. Main differences between Spring AOP and AspectJ are:

  • Spring AOP is simpler to use than AspectJ because we don’t need to worry about the weaving process.
  • Spring AOP supports AspectJ annotations, so if you are familiar with AspectJ then working with Spring AOP is easier.
  • Spring AOP supports only proxy-based AOP, so it can be applied only to method execution join points. AspectJ support all kinds of pointcuts.
  • One of the shortcomings of Spring AOP is that it can be applied only to the beans created through Spring Context.

How to access request, session, global session scoped beans without dispatcher servlet in Spring ?

To support the scoping of beans at the request, session, and global session levels (web-scoped beans), some minor initial configuration is required before defining your beans. This initial setup is not required for the standard scopes, singleton and prototype.

If you access scoped beans within Spring Web MVC, in effect, within a request that is processed by the Spring DispatcherServlet, or DispatcherPortlet, then no special setup is necessary: DispatcherServlet and DispatcherPortlet already expose all relevant state.

Add the following declaration to your web application’s web.xml file

<web-app>
    ...
    <listener>
        <listener-class>
            org.springframework.web.context.request.RequestContextListener
        </listener-class>
    </listener>
    ...
</web-app>

For servlet 3.0+, this can done programmatically via the WebApplicationInitializer interface.

If there is any issue setting up the above listener then you can use the following

<web-app>
    ...
    <filter>
        <filter-name>requestContextFilter</filter-name>
        <filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>requestContextFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    ...
</web-app>

What are the benefits of Spring transactions?

The benefits of using Spring Transactions are:

  • Provide a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO
  • Support declarative transaction management
  • Provide a simpler API for programmatic transaction management than some complex transaction APIs such as JTA
  • Integrate very well with Spring’s various data access abstractions