0%

1. Overview

Before we get started with the implementation, it’s important to point out that the primary List and Set collection interfaces extend Collection but Map does not.

Simply put, the HashMap stores values by key and provides APIs for adding, retrieving and manipulating stored data in various ways. The implementation is based on the the principles of a hashtable, which sounds a little complex at first but is actually very easy to understand.

Key-value pairs are stored in what is known as buckets which together make up what is called a table, which is actually an internal array.

Once we know the key under which an object is stored or is to be stored, storage and retrieval operations occur in constant time, O(1) in a well-dimensioned hash map.

To understand how hash maps work under the hood, one needs to understand the storage and retrieval mechanism employed by the HashMap. We’ll focus a lot on these.

Finally, HashMap\ related questions are quite common in interviews, so this is a solid way to either prepare an interview or prepare for it.

2. The put() API

To store a value in a hash map, we call the put API which takes two parameters; a key and the corresponding value:

1
V put(K key, V value);

When a value is added to the map under a key, the hashCode() API of the key object is called to retrieve what is known as the initial hash value.

To see this in action, let us create an object that will act as a key. We will only create a single attribute to use as a hash code to simulate the first phase of hashing:

1
2
3
4
5
6
7
8
9
10
11
public class MyKey {
private int id;

@Override
public int hashCode() {
System.out.println("Calling hashCode()");
return id;
}

// constructor, setters and getters
}

We can now use this object to map a value in the hash map:

1
2
3
4
5
6
@Test
public void whenHashCodeIsCalledOnPut_thenCorrect() {
MyKey key = new MyKey(1);
Map<MyKey, String> map = new HashMap<>();
map.put(key, "val");
}

Nothing much happening in the above code, but pay attention to the console output. Indeed the hashCode method gets invoked:

1
Calling hashCode()

Next, the hash() API of the hash map is called internally to compute the final hash value using the initial hash value.

This final hash value ultimately boils down to an index in the internal array or what we call a bucket location.

The hash function of HashMap looks like this:

1
2
3
4
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

What we should note here is only the use of the hash code from the key object to compute a final hash value.

While inside the put function, the final hash value is used like this:

1
2
3
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}

Notice that an internal putVal function is called and given the final hash value as the first parameter.

One may wonder why the key is again used inside this function since we have already used it to compute the hash value.

The reason is that hash maps store both key and value in the bucket location as a *Map.Entry* object.

As discussed before, all Java collections framework interfaces extend Collection interface but Map does not. Compare the declaration of Map interface we saw earlier to that of Set interface:

1
public interface Set<E> extends Collection<E>

The reason is that maps do not exactly store single elements as do other collections but rather a collection of key-value pairs.

So the generic methods of Collection interface such as add, toArray do not make sense when it comes to Map.

The concept we have covered in the last three paragraphs makes for one of the most popular Java Collections Framework interview questions. So, it’s worth understanding.

One special attribute with the hash map is that it accepts null values and null keys:

1
2
3
4
5
@Test
public void givenNullKeyAndVal_whenAccepts_thenCorrect(){
Map<String, String> map = new HashMap<>();
map.put(null, null);
}

When a null key is encountered during a *put* operation, it is automatically assigned a final hash value of *0*, which means it becomes the first element of the underlying array.

This also means that when the key is null, there is no hashing operation and therefore, the hashCode API of the key is not invoked, ultimately avoiding a null pointer exception.

During a put operation, when we use a key that was already used previously to store a value, it returns the previous value associated with the key:

1
2
3
4
5
6
7
8
9
@Test
public void givenExistingKey_whenPutReturnsPrevValue_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("key1", "val1");

String rtnVal = map.put("key1", "val2");

assertEquals("val1", rtnVal);
}

otherwise, it returns null:

1
2
3
4
5
6
7
8
@Test
public void givenNewKey_whenPutReturnsNull_thenCorrect() {
Map<String, String> map = new HashMap<>();

String rtnVal = map.put("key1", "val1");

assertNull(rtnVal);
}

When put returns null, it could also mean that the previous value associated with the key is null, not necessarily that it’s a new key-value mapping:

1
2
3
4
5
6
7
8
@Test
public void givenNullVal_whenPutReturnsNull_thenCorrect() {
Map<String, String> map = new HashMap<>();

String rtnVal = map.put("key1", null);

assertNull(rtnVal);
}

The containsKey API can be used to distinguish between such scenarios as we will see in the next subsection.

3. The get API

To retrieve an object already stored in the hash map, we must know the key under which it was stored. We call the get API and pass to it the key object:

1
2
3
4
5
6
7
8
9
@Test
public void whenGetWorks_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("key", "val");

String val = map.get("key");

assertEquals("val", val);
}

Internally, the same hashing principle is used. The hashCode() API of the key object is called to obtain the initial hash value:

1
2
3
4
5
6
7
@Test
public void whenHashCodeIsCalledOnGet_thenCorrect() {
MyKey key = new MyKey(1);
Map<MyKey, String> map = new HashMap<>();
map.put(key, "val");
map.get(key);
}

This time, the hashCode API of MyKey is called twice; once for put and once for get:

1
2
Calling hashCode()
Calling hashCode()

This value is then rehashed by calling the internal hash() API to obtain the final hash value.

As we saw in the previous section, this final hash value ultimately boils down to a bucket location or an index of the internal array.

The value object stored in that location is then retrieved and returned to the calling function.

When the returned value is null, it could mean that the key object is not associated with any value in the hash map:

1
2
3
4
5
6
7
8
@Test
public void givenUnmappedKey_whenGetReturnsNull_thenCorrect() {
Map<String, String> map = new HashMap<>();

String rtnVal = map.get("key1");

assertNull(rtnVal);
}

Or it could simply mean that the key was explicitly mapped to a null instance:

1
2
3
4
5
6
7
8
9
@Test
public void givenNullVal_whenRetrieves_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("key", null);

String val=map.get("key");

assertNull(val);
}

To distinguish between the two scenarios, we can use the containsKey API, to which we pass the key and it returns true if and only if a mapping was created for the specified key in the hash map:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
public void whenContainsDistinguishesNullValues_thenCorrect() {
Map<String, String> map = new HashMap<>();

String val1 = map.get("key");
boolean valPresent = map.containsKey("key");

assertNull(val1);
assertFalse(valPresent);

map.put("key", null);
String val = map.get("key");
valPresent = map.containsKey("key");

assertNull(val);
assertTrue(valPresent);
}

For both cases in the above test, the return value of the get API call is null but we are able to distinguish which one is which.

4. Collection Views in HashMap

HashMap offers three views that enable us to treat its keys and values as another collection. We can get a set of all keys of the map:

1
2
3
4
5
6
7
8
9
10
11
12
@Test
public void givenHashMap_whenRetrievesKeyset_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("name", "yc");
map.put("type", "blog");

Set<String> keys = map.keySet();

assertEquals(2, keys.size());
assertTrue(keys.contains("name"));
assertTrue(keys.contains("type"));
}

The set is backed by the map itself. So any change made to the set is reflected in the map:

1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
public void givenKeySet_whenChangeReflectsInMap_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("name", "yc");
map.put("type", "blog");

assertEquals(2, map.size());

Set<String> keys = map.keySet();
keys.remove("name");

assertEquals(1, map.size());
}

We can also obtain a collection view of the values:

1
2
3
4
5
6
7
8
9
10
11
12
@Test
public void givenHashMap_whenRetrievesValues_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("name", "baeldung");
map.put("type", "blog");

Collection<String> values = map.values();

assertEquals(2, values.size());
assertTrue(values.contains("yc"));
assertTrue(values.contains("blog"));
}

Just like the key set, any changes made in this collection will be reflected in the underlying map.

Finally, we can obtain a set view of all entries in the map:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
public void givenHashMap_whenRetrievesEntries_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("name", "yc");
map.put("type", "blog");

Set<Entry<String, String>> entries = map.entrySet();

assertEquals(2, entries.size());
for (Entry<String, String> e : entries) {
String key = e.getKey();
String val = e.getValue();
assertTrue(key.equals("name") || key.equals("type"));
assertTrue(val.equals("yc") || val.equals("blog"));
}
}

Remember that a hash map specifically contains unordered elements, therefore we assume any order when testing the keys and values of entries in the for each loop.

Many times, you will use the collection views in a loop as in the last example, and more specifically using their iterators.

Just remember that the iterators for all the above views are *fail-fast*.

If any structural modification is made on the map, after the iterator has been created, a concurrent modification exception will be thrown:

1
2
3
4
5
6
7
8
9
10
11
12
13
@Test(expected = ConcurrentModificationException.class)
public void givenIterator_whenFailsFastOnModification_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("name", "yc");
map.put("type", "blog");

Set<String> keys = map.keySet();
Iterator<String> it = keys.iterator();
map.remove("type");
while (it.hasNext()) {
String key = it.next();
}
}

The only allowed structural modification is a *remove* operation performed through the iterator itself:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public void givenIterator_whenRemoveWorks_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("name", "yc");
map.put("type", "blog");

Set<String> keys = map.keySet();
Iterator<String> it = keys.iterator();

while (it.hasNext()) {
it.next();
it.remove();
}

assertEquals(0, map.size());
}

The final thing to remember about these collection views is the performance of iterations. This is where a hash map performs quite poorly compared with its counterparts linked hash map and tree map.

Iteration over a hash map happens in worst case O(n) where n is the sum of its capacity and the number of entries.

5. HashMap Performance

The performance of a hash map is affected by two parameters: Initial Capacity and Load Factor. The capacity is the number of buckets or the underlying array length and the initial capacity is simply the capacity during creation.

The load factor or LF, in short, is a measure of how full the hash map should be after adding some values before it is resized.

The default initial capacity is 16 and default load factor is 0.75. We can create a hash map with custom values for initial capacity and LF:

1
2
Map<String,String> hashMapWithCapacity=new HashMap<>(32);
Map<String,String> hashMapWithCapacityAndLF=new HashMap<>(32, 0.5f);

The default values set by the Java team are well optimized for most cases. However, if you need to use your own values, which is very okay, you need to understand the performance implications so that you know what you are doing.

When the number of hash map entries exceeds the product of LF and capacity, then rehashing occurs i.e. another internal array is created with twice the size of the initial one and all entries are moved over to new bucket locations in the new array.

A low initial capacity reduces space cost but increases the frequency of rehashing. Rehashing is obviously a very expensive process. So as a rule, if you anticipate many entries, you should set a considerably high initial capacity.

On the flip side, if you set the initial capacity too high, you will pay the cost in iteration time. As we saw in the previous section.

So a high initial capacity is good for a large number of entries coupled with little to no iteration.

A low initial capacity is good for few entries with a lot of iteration.

*6. Collisions in the HashMap

A collision, or more specifically, a hash code collision in a HashMap, is a situation where two or more key objects produce the same final hash value and hence point to the same bucket location or array index.

This scenario can occur because according to the equals and hashCode contract, two unequal objects in Java can have the same hash code.

It can also happen because of the finite size of the underlying array, that is, before resizing. The smaller this array, the higher the chances of collision.

That said, it’s worth mentioning that Java implements a hash code collision resolution technique which we will see using an example.

Keep in mind that it’s the hash value of the key that determines the bucket the object will be stored in. And so, if the hash codes of any two keys collide, their entries will still be stored in the same bucket.

And by default, the implementation uses a linked list as the bucket implementation.

The initially constant time O(1) put and get operations will occur in linear time O(n) in the case of a collision. This is because after finding the bucket location with the final hash value, each of the keys at this location will be compared with the provided key object using the equals API.

To simulate this collision resolution technique, let’s modify our earlier key object a little:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class MyKey {
private String name;
private int id;

public MyKey(int id, String name) {
this.id = id;
this.name = name;
}

// standard getters and setters

@Override
public int hashCode() {
System.out.println("Calling hashCode()");
return id;
}

// toString override for pretty logging

@Override
public boolean equals(Object obj) {
System.out.println("Calling equals() for key: " + obj);
// generated implementation
}

}

Notice how we’re simply returning the id attribute as the hash code – and thus force a collision to occur.

Also, note that we’ve added log statements in our equals and hashCode implementations – so that we know exactly when the logic is called.

Let’s now go ahead to store and retrieve some objects that collide at some point:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@Test
public void whenCallsEqualsOnCollision_thenCorrect() {
HashMap<MyKey, String> map = new HashMap<>();
MyKey k1 = new MyKey(1, "firstKey");
MyKey k2 = new MyKey(2, "secondKey");
MyKey k3 = new MyKey(2, "thirdKey");

System.out.println("storing value for k1");
map.put(k1, "firstValue");
System.out.println("storing value for k2");
map.put(k2, "secondValue");
System.out.println("storing value for k3");
map.put(k3, "thirdValue");

System.out.println("retrieving value for k1");
String v1 = map.get(k1);
System.out.println("retrieving value for k2");
String v2 = map.get(k2);
System.out.println("retrieving value for k3");
String v3 = map.get(k3);

assertEquals("firstValue", v1);
assertEquals("secondValue", v2);
assertEquals("thirdValue", v3);
}

In the above test, we create three different keys – one has a unique id and the other two have the same id. Since we use id as the initial hash value, there will definitely be a collision during both storage and retrieval of data with these keys.

In addition to that, thanks to the collision resolution technique we saw earlier, we expect each of our stored values to be retrieved correctly, hence the assertions in the last three lines.

When we run the test, it should pass, indicating that collisions were resolved and we will use the logging produced to confirm that the collisions indeed occurred:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
storing value for k1
Calling hashCode()
storing value for k2
Calling hashCode()
storing value for k3
Calling hashCode()
Calling equals() for key: MyKey [name=secondKey, id=2]
retrieving value for k1
Calling hashCode()
retrieving value for k2
Calling hashCode()
retrieving value for k3
Calling hashCode()
Calling equals() for key: MyKey [name=secondKey, id=2]

Notice that during storage operations, k1 and k2 were successfully mapped to their values using only the hash code.

However, storage of k3 was not so simple, the system detected that its bucket location already contained a mapping for k2. Therefore, equals comparison was used to distinguish them and a linked list was created to contain both mappings.

Any other subsequent mapping whose key hashes to the same bucket location will follow the same route and end up replacing one of the nodes in the linked list or be added to the head of the list if equals comparison returns false for all existing nodes.

Likewise, during retrieval, k3 and k2 were equals-compared to identify the correct key whose value should be retrieved.

On a final note, from Java 8, the linked lists are dynamically replaced with balanced binary search trees in collision resolution after the number of collisions in a given bucket location exceed a certain threshold.

This change offers a performance boost, since, in the case of a collision, storage and retrieval happen in O(log n).

This section is very common in technical interviews, especially after the basic storage and retrieval questions.

Spring Interview Questions And Answers

Q1) What is Spring?

Spring is an open-source development framework for Enterprise Java. The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make Java EE development easier to use and promote good programming practice by enabling a POJO-based programming model.

Q2) What are benefits of Spring Framework?

  1. Lightweight: Spring is lightweight when it comes to size and transparency. The basic version of the spring framework is around 2MB.
  2. Inversion of control (IOC): Loose coupling is achieved in Spring, with the Inversion of Control technique. The objects give their dependencies instead of creating or looking for dependent objects.
  3. Aspect oriented (AOP): Spring supports Aspect oriented programming and separates application business logic from system services.
  4. Container: Spring contains and manages the life cycle and configuration of application objects.
  5. MVC Framework: Spring’s web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks.
  6. Transaction Management: Spring provides a consistent transaction management interface that can scale down to a local transaction and scale up to global transactions (JTA).
  7. Exception Handling: Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO) into consistent, unchecked exceptions.

Q3) Which are the Spring framework modules?

The basic modules of the Spring framework are :

  1. Core module
  2. Bean module
  3. Context module
  4. Expression Language module
  5. JDBC module
  6. ORM module
  7. OXM module
  8. Java Messaging Service(JMS) module
  9. Transaction module
  10. Web module
  11. Web-Servlet module
  12. Web-Struts module
  13. Web-Portlet module

Q4) Explain the Core Container (Application context) module

This is the basic Spring module, which provides the fundamental functionality of the Spring framework. BeanFactory is the heart of any spring-based application. Spring framework was built on the top of this module, which makes the Spring container.

Q5) What is BeanFactory – BeanFactory implementation example

A BeanFactory is an implementation of the factory pattern that applies Inversion of Control to separate the application’s configuration and dependencies from the actual application code.
The most commonly used BeanFactory implementation is the XmlBeanFactory class.

Q6) XMLBeanFactory

The most useful one is org.springframework.beans.factory.xml.XmlBeanFactory, which loads its beans based on the definitions contained in an XML file. This container reads the configuration metadata from an XML file and uses it to create a fully configured system or application.

Q7) Explain the AOP module

The AOP module is used for developing aspects for our Spring-enabled application. Much of the support has been provided by the AOP Alliance in order to ensure the interoperability between Spring and other AOP frameworks. This module also introduces metadata programming to Spring.

Q8) Explain the JDBC abstraction and DAO module

With the JDBC abstraction and DAO module we can be sure that we keep up the database code clean and simple, and prevent problems that result from a failure to close database resources. It provides a layer of meaningful exceptions on top of the error messages given by several database servers. It also makes use of Spring’s AOP module to provide transaction management services for objects in a Spring application.

Q9) Explain the object/relational mapping integration module

Spring also supports for using of an object/relational mapping (ORM) tool over straight JDBC by providing the ORM module. Spring provides support to tie into several popular ORM frameworks, including Hibernate, JDO, and iBATIS SQL Maps. Spring’s transaction management supports each of these ORM frameworks as well as JDBC.

Q10) Explain the web module

The Spring web module is built on the application context module, providing a context that is appropriate for web-based applications. This module also contains support for several web-oriented tasks such as transparently handling multipart requests for file uploads and programmatic binding of request parameters to your business objects. It also contains integration support with Jakarta Struts.

Q11) Explain the Spring MVC module

MVC framework is provided by Spring for building web applications. Spring can easily be integrated with other MVC frameworks, but Spring’s MVC framework is a better choice, since it uses IoC to provide for a clean separation of controller logic from business objects. With Spring MVC you can declaratively bind request parameters to your business objects.

Q12) Spring configuration file

Spring configuration file is an XML file. This file contains the classes information and describes how these classes are configured and introduced to each other.

Q13) What is Spring IoC container?

The Spring IoC is responsible for creating the objects,managing them (with dependency injection (DI)), wiring them together, configuring them, as also managing their complete lifecycle.

Q14) What are the benefits of IOC?

IOC or dependency injection minimizes the amount of code in an application. It makes easy to test applications, since no singletons or JNDI lookup mechanisms are required in unit tests. Loose coupling is promoted with minimal effort and least intrusive mechanism. IOC containers support eager instantiation and lazy loading of services.

Q15) What are the common implementations of the ApplicationContext?

The FileSystemXmlApplicationContext container loads the definitions of the beans from an XML file. The full path of the XML bean configuration file must be provided to the constructor.

The ClassPathXmlApplicationContext container also loads the definitions of the beans from an XML file. Here, you need to set CLASSPATH properly because this container will look bean configuration XML file in CLASSPATH.

The WebXmlApplicationContext: container loads the XML file with definitions of all beans from within a web application.

Q16) What is the difference between Bean Factory and ApplicationContext?

Application contexts provide a means for resolving text messages, a generic way to load file resources (such as images), they can publish events to beans that are registered as listeners. In addition, operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context. The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable.

Q17) What does a Spring application look like?

  1. An interface that defines the functions.
  2. The implementation that contains properties, its setter and getter methods, functions etc.,
  3. Spring AOP
  4. The Spring configuration XML file.
  5. Client program that uses the function

Q18) What is Dependency Injection in Spring?

Dependency Injection, an aspect of Inversion of Control (IoC), is a general concept, and it can be expressed in many different ways.This concept says that you do not create your objects but describe how they should be created. You don’t directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (the IOC container) is then responsible for hooking it all up.

Q19) What are the different types of IoC (dependency injection)?

  1. Constructor-based dependency injection: Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.
  2. Setter-based dependency injection: Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.

Q20) Which DI would you suggest Constructor-based or setter-based DI?

You can use both Constructor-based and Setter-based Dependency Injection. The best solution is using constructor arguments for mandatory dependencies and setters for optional dependencies.

Q21) What are Spring beans?

Spring beans scope interview questions - The Spring Beans are Java Objects that form the backbone of a Spring application. They are instantiated, assembled, and managed by the Spring IoC container. These beans are created with the configuration metadata that is supplied to the container, for example, in the form of XML definitions.

Beans defined in spring framework are singleton beans. There is an attribute in bean tag named “singleton” if specified true then bean becomes singleton and if set to false then the bean becomes a prototype bean. By default it is set to true. So, all the beans in spring framework are by default singleton beans.

Q22) What does a Spring Bean definition contain?

A Spring Bean definition contains all configuration metadata which is needed for the container to know how to create a bean, its lifecycle details and its dependencies.

Q23) How do you provide configuration metadata to the Spring Container?

There are three important methods to provide configuration metadata to the Spring Container:

  1. XML based configuration file.
  2. Annotation-based configuration
  3. Java-based configuration

Q24) How do you define the scope of a bean?

When defining a in Spring, we can also declare a scope for the bean. It can be defined through the scope attribute in the bean definition. For example, when Spring has to produce a new bean instance each time one is needed, the bean’sscope attribute to be prototype. On the other hand, when the same instance of a bean must be returned by Spring every time it is needed, the the bean scope attribute must be set to singleton.

Q25) Explain the bean scopes supported by Spring

There are five scoped provided by the Spring Framework supports following five scopes:

  1. In singlet on scope, Spring scopes the bean definition to a single instance per Spring IoC container.
  2. In prototype scope, a single bean definition has any number of object instances.
  3. In request scope, a bean is defined to an HTTP request. This scope is valid only in a web-aware Spring ApplicationContext.
  4. In session scope, a bean definition is scoped to an HTTP session. This scope is also valid only in a web-aware Spring ApplicationContext.
  5. In global-session scope, a bean definition is scoped to a global HTTP session. This is also a case used in a web-aware Spring ApplicationContext.

The default scope of a Spring Bean is Singleton.

Q26) Are Singleton beans thread safe in Spring Framework?

No, singleton beans are not thread-safe in Spring framework.

Q27) Explain Bean lifecycle in Spring framework

  1. The spring container finds the bean’s definition from the XML file and instantiates the bean.
  2. Spring populates all of the properties as specified in the bean definition (DI).
  3. If the bean implementsBeanNameAware interface, spring passes the bean’s id to setBeanName()
  4. If Bean implementsBeanFactoryAware interface, spring passes the beanfactory to setBeanFactory()
  5. If there are any beanBeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization()
  6. If the bean implementsIntializingBean, its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called.
  7. If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
  8. If the bean implementsDisposableBean, it will call the destroy()

Q28) Which are the important beans lifecycle methods? Can you override them?

There are two important bean lifecycle methods. The first one is setup which is called when the bean is loaded in to the container. The second method is the teardown method which is called when the bean is unloaded from the container.

The bean tag has two important attributes (init-method and destroy-method) with which you can define your own custom initialization and destroy methods. There are also the correspondive annotations(@PostConstruct and @PreDestroy).

Q29) What are inner beans in Spring?

When a bean is only used as a property of another bean it can be declared as an inner bean. Spring’s XML-based configuration metadata provides the use of element inside the or elements of a bean definition, in order to define the so-called inner bean. Inner beans are always anonymous and they are always scoped as prototypes.

Q30) How can you inject a Java Collection in Spring?

Spring offers the following types of collection configuration elements:

  1. The type is used for injecting a list of values, in the case that duplicates are allowed.
  2. The type is used for wiring a set of values but without any duplicates.
  3. The type is used to inject a collection of name-value pairs where name and value can be of any type.
  4. The type can be used to inject a collection of name-value pairs where the name and value are both Strings.

Q31) What is bean wiring?

Wiring, or else bean wiring is the case when beans are combined together within the Spring container. When wiring beans, the Spring container needs to know what beans are needed and how the container should use dependency injection to tie them together.

Q32) What is bean auto wiring?

The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for a bean by inspecting the contents of the BeanFactorywithout using and elements.

Q33) Explain different modes of auto wiring?

The autowiring functionality has five modes which can be used to instruct Spring container to use autowiring for dependency injection:

  1. no: This is default setting. Explicit bean reference should be used for wiring.
  2. byName: When autowiring byName, the Spring container looks at the properties of the beans on which autowireattribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file.
  3. byType: When autowiring by datatype, the Spring container looks at the properties of the beans on which autowireattribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exist, a fatal exception is thrown.
  4. constructor:This mode is similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.
  5. autodetect: Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire bybyType.

Q34) Are there limitations with autowiring?

Limitations of autowiring are:

  1. Overriding: You can still specify dependencies using and settings which will always override autowiring.
  2. Primitive data types: You cannot autowire simple properties such as primitives, Strings, and Classes.
  3. Confusing nature: Autowiring is less exact than explicit wiring, so if possible prefer using explicit wiring.

Q35) Can you inject null and empty string values in Spring?

Yes, you can.

Q36) What is Spring Java-Based Configuration? Give some annotation example.

Java based configuration option enables you to write most of your Spring configuration without XML but with the help of few Java-based annotations.

An example is a @Configuration annotation, that indicates that the class can be used by the Spring IoC container as a source of bean definitions. Another example is the@Bean annotated method that will return an object that should be registered as a bean in the Spring application context.

Q36) What is Annotation-based container configuration?

An alternative to XML setups is provided by an annotation-based configuration which relies on the bytecode metadata for wiring up components instead of angle-bracket declarations. Instead of using XML to describe a bean wiring, the developer moves the configuration into the component class itself by using annotations on the relevant class, method, or field declaration.

Q37) How do you turn on annotation wiring?

Annotation wiring is not turned on in the Spring container by default. In order to use annotation based wiring, we must enable it in our Spring configuration file by configuring element.

Q38) @Required annotation

This annotation simply indicates that the affected bean property must be populated at configuration time, through an explicit property value in a bean definition or through autowiring. The container throws BeanInitializationException if the affected bean property has not been populated.

Q39) @Autowired annotation

The @Autowired annotation provides more fine-grained control over where and how autowiring should be accomplished. It can be used to autowire bean on the setter method just like @Required annotation, on the constructor, on a property or pn methods with arbitrary names and/or multiple arguments.

Q40) @Qualifier annotation

When there are more than one beans of the same type and only one is needed to be wired with a property, the@Qualifier annotation is used along with @Autowired annotation to remove the confusion by specifying which exact bean will be wired.

Q41) How can JDBC be used more efficiently in the Spring framework?

When using the Spring JDBC framework the burden of resource management and error handling is reduced. So developers only need to write the statements and queries to get the data to and from the database. JDBC can be used more efficiently with the help of a template class provided by Spring framework, which is the JdbcTemplate

Q42) JdbcTemplate

JdbcTemplate class provides many convenience methods for doing things such as converting database data into primitives or objects, executing prepared and callable statements, and providing custom database error handling.

Q43) Spring DAO support

The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies like JDBC, Hibernate or JDO in a consistent way. This allows us to switch between the persistence technologies fairly easily and to code without worrying about catching exceptions that are specific to each technology.

Q44) What are the ways to access Hibernate by using Spring?

There are two ways to access Hibernate with Spring:

  1. Inversion of Control with a Hibernate Template and Callback.
  2. ExtendingHibernateDAOSupport and Applying an AOP Interceptor node.

Q45) ORM’s Spring support

Spring supports the following ORM’s:

  1. Hibernate
  2. iBatis
  3. JPA (Java Persistence API)
  4. TopLink
  5. JDO (Java Data Objects)
  6. OJB

Q46) How can we integrate Spring and Hibernate using HibernateDaoSupport?

Use Spring’s SessionFactory called LocalSessionFactory. The integration process is of 3 steps:

  1. Configure the Hibernate SessionFactory
  2. Extend a DAO Implementation fromHibernateDaoSupport
  3. Wire in Transaction Support with AOP

Q47) Types of the transaction management Spring support

Spring supports two types of transaction management:

  1. Programmatic transaction management: This means that you have managed the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain.
  2. Declarative transaction management: This means you separate transaction management from the business code. You only use annotations or XML based configuration to manage the transactions.

Q48) What are the benefits of the Spring Framework’s transaction management?

  1. It provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO.
  2. It provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA.
  3. It supports declarative transaction management.
  4. It integrates very well with Spring’s various data access abstractions.

Q49) Which Transaction management type is more preferable?

Most users of the Spring Framework choose declarative transaction management because it is the option with the least impact on application code, and hence is most consistent with the ideals of a non-invasive lightweight container. Declarative transaction management is preferable over programmatic transaction management though it is less flexible than programmatic transaction management, which allows you to control transactions through your code.

Q50) Explain AOP

Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns or behavior that cuts across the typical divisions of responsibility, such as logging and transaction management.

Q51) Aspect

The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules. It ia a module which has a set of APIs providing cross-cutting requirements. For example, a logging module would be called AOP aspect for logging. An application can have any number of aspects depending on the requirement. In Spring AOP, aspects are implemented using regular classes annotated with the @Aspect annotation (@AspectJ style).

Q52) What is the difference between concern and cross-cutting concern in Spring AOP

The Concern is behavior we want to have in a module of an application. A Concern may be defined as a functionality we want to implement.

The cross-cutting concern is a concern which is applicable throughout the application and it affects the entire application. For example, logging, security and data transfer are the concerns which are needed in almost every module of an application, hence they are cross-cutting concerns.

Q53) Joinpoint

The join point represents a point in an application where we can plug-in an AOP aspect. It is the actual place in the application where an action will be taken using Spring AOP framework.

Q54) Advice

The advice is the actual action that will be taken either before or after the method execution. This is an actual piece of code that is invoked during the program execution by the Spring AOP framework.
Spring aspects can work with five kinds of advice:

  1. before: Run advice before the method execution.
  2. after: Run advice after the method execution regardless of its outcome.
  3. after-returning: Run advice after the method execution only if method completes successfully.
  4. after-throwing: Run advice after the method execution only if a method exits by throwing an exception.
  5. around: Run advice before and after the advised method is invoked.

Q55) Pointcut

The pointcut is a set of one or more joinpoints where an advice should be executed. You can specify pointcuts using expressions or patterns.

Q56) What is Introduction?

An Introduction allows us to add new methods or attributes to existing classes.

Q57) What is Target object?

A target object is an object being advised by one or more aspects. It will always be a proxy object. It is also referred to as the advised object.

Q58) What is a Proxy?

A proxy is an object that is created by applying advice to a target object. When you think of client objects the target object and the proxy object are the same.

Q59) What are the different types of AutoProxying?

  1. BeanNameAutoProxyCreator
  2. DefaultAdvisorAutoProxyCreator
  3. Metadata autoproxying

Q60) What is Weaving? What are the different points where weaving can be applied?

Weaving is the process of linking aspects with other application types or objects to create an advised object.

Weaving can be done at compile time, at load time, or at runtime.

Q61) Explain XML Schema-based aspect implementation?

In this implementation case, aspects are implemented using regular classes along with XML based configuration.

Q62) Explain annotation-based (@AspectJ based) aspect implementation

This implementation case (@AspectJ based implementation) refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations.

Q63) What is Spring MVC framework?

Spring comes with a full-featured MVC framework for building web applications. Although Spring can easily be integrated with other MVC frameworks, such as Struts, Spring’s MVC framework uses IoC to provide a clean separation of controller logic from business objects. It also allows to declaratively bind request parameters to business objects.

Q64) DispatcherServlet

The Spring Web MVC framework is designed around a DispatcherServlet that handles all the HTTP requests and responses.

Q65) WebApplicationContext

The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features necessary for web applications. It differs from a normal ApplicationContext in that it is capable of resolving themes, and that it knows which servlet it is associated with.

Q66) What is Controller in Spring MVC framework?

Controllers provide access to the application behavior that you typically define through a service interface. Controllers interpret user input and transform it into a model that is represented to the user by the view. Spring implements a controller in a very abstract way, which enables you to create a wide variety of controllers.

Q67) @Controller annotation

The @Controller annotation indicates that a particular class serves the role of a controller. Spring does not require you to extend any controller base class or reference the Servlet API.

In this article, you will learn about why is programming skills important, what are its uses in technology, and how it impacts business and career. The programming skill is important for learning to innovate, create eco-friendly solutions for global problems. Programming is important in our daily life to enhance and increase the power of computers and the internet.

Programming is important for speeding up the input and output processes in a machine. Programming is important to automate, collect, manage, calculate, analyze the processing of data and information accurately.

Programming is important to create software and applications that help computer and mobile users in daily life. Due to all these reasons, it’s really important to learn how to use programming languages in our daily life.

Java, javascript, C#, C++, PHP, Python, Swift, SQL, Ruby, etc. programming languages are the reasons behind the innovations in information technologies. If today we are seeing robots, artificial intelligence, machine learning, bitcoins, blockchain, IoT (Internet of Things), Cloud Computing, etc. new technology and products in the IT industry, then it’s because of programming languages.

The group of programs is called software. Programming languages are the way to create software that performs various or specific tasks in a systematic manner. Software development is like a Marriage event.

A programming language is a method to communicate with machines in a systematic format. To understand programming languages first we need to start from programs.

What is a program?

A program is a group of logical, mathematical, systematical, and managed functions grouped together to perform a specific task. Just like there are various programs in the marriage such as Shanti, Barat Prasthan, Lagan, Vadhu Pravesh, reception, Dham, etc.

What is a function?

Groups of classes are called a function. A function requires specific classes. For example, if you want to create a function to play songs then you need to create specific classes under these programs in which play, pause, stop and etc. are the classes. Now in a marriage example, the Shanti program contains various functions such as mama swagat, batna lepan, lok sangit, sehra bandi are various functions inside the Shanti program. That’s why small and big functions are important in a programming language to create software.

What is class?

Now each class contains a group of instruction and commands. There are variables, integers, decimals, symbols, loops, if/else, logical methods, and certain leaders in the class. All that is aimed to perform a specific task on the computer and the internet automatically. Similarly, in Sehra Bandhi, the Sehra is given by Mama’s to the bridegroom, it’s placed by parents and pandit pronounce the certain mantras. Now, this process takes time and all things go smoothly. Now I think you must have got a clear idea, how the classes are created or programmed using programming languages. That’s why classes are so much important in a programming language to create functions.

I want to take you a little deeper into the programming languages so that you automatically understand why it is important. As you learned above in the last point about the classes and group of instruction and commands.

Now, What is instruction or command?

Instruction or commands are the systematic methods to operate certain machines. Just as we give instructions to the computer using a keyboard and mouse. Similarly, during sehra bandi, vadhu pravesh, lagna we use certain objects such as dhoop, chawal, kusha, water, haldi, and other religious products to perform that specific action.

So to perform certain tasks on the computer we use input devices and in the same methods, we instruct computers and machines in the classes, functions, programs, and software to perform those tasks. So that we don’t need to do the task again and again. Instead, the software can do it automatically with high speed and accuracy. And we use a programming language to create software that performs and receives inputs.
Each event contains different smaller programs. Such as Retirement programs contain different smaller functions and even birthday parties contain different programs, functions, and classes.

Similarly, each software contains different programs, functions, classes, and instruction. So for Android programs, functions and classes are different than Mac Os programs. For the same example, we have adobe photoshop software programs, classes, libraries, and functions, which are different than Microsoft office 360.

Similarly, the Facebook website is an application in which programs, functions, classes are different than the WordPress website.

All web applications and software are created using programming languages and the languages can be similar or different or many languages in a single class. It’s not about how many programming languages you use in a single class. It’s just about doing this in a way so that the language is acceptable, instructional, and logical to automate the process.

Similarly, in a marriage function in a class in which ‘Lagan’ is going on and Pundit pronounces mantras in Sanskrit language only, but in other countries the similar process of Lagana is different and the language can be English and prayer or blessings are done by a priest in a church.

In this way with the example of marriage, you will be able to understand the importance of programming language. As marriage is important in our life programming is important to create and run software and information technology.

Now the above example helped you to understand what is a programming language and its importance. Now it’s important that you also understand a different perspective of the importance of programming languages in this article, we always want our readers will get maximum information and knowledge. So that’s why we not only write in creative and technical methods but also write with variety.

Now from a career perspective, the importance of learning programming languages is bigger and higher than any other IT subject for students. As you learned above that to innovate and to create software it’s important to use programming language.

Now if kids, school, and college students learn programming languages as early as possible, it will greatly help them to create next big things like WhatsApp, Facebook, Google, and many other applications that are in the race to influence and change the world.

Even if students don’t want to create their own applications and next viral apps they can easily get a job in the city. Almost every IT company requires skilled programmers. Small companies require an array of wider programming skills whereas big companies require very specific skills with predefined targets.

Now the software development has many parts as I discussed above with the marriage example. When we look for a career in software development or programming field, we need to differentiate our skill and programming training in a way so that it remains relevant and specific for the job.

So if we take Marriage as an analogy of software, then it’s important to know if you want to become Pundit, tent and decoration supplier, event manager, DJ, or the whole event planner.

Similarly, in software and web development it requires planning, execution, management, inventory, support, sales, and marketing. So it’s important when you look for a career you need to have expertise in the skills. Such as an expert in Javascript, Expert in Python web development, an expert in SQL Lite, etc. So the demand of programmers in the IT field and the various industry is big, so it’s not a doubt that learning programming languages will provide you a high return on time, effort, and financial investment.

While there are other reasons behind why one should learn programming languages, we conclude in a short paragraph. We can say that programming languages are important to create software and programming languages are important to create and implement certain functionality in machines. Programming languages are important to create solutions that are environmentally friendly and support the highest level of living standards for humans.

It’s also important to program a world that helps to reduce corruption, improves transparency and happiness in everyone’s life. Programming languages are now a part of our life. Learning can never be wrong, but purposeful learning helps in a great way for students, businesses and all human beings. It’s should be done to support nature not to disturb it.

1. Introduction

In this article, we’re going to look at some of the most common Spring-related questions that might pop up during a job interview.

2. Spring Core

Q1. What Is Spring Framework?

Spring is the most broadly used framework for the development of Java Enterprise Edition applications. The core features of Spring can be used in developing any Java application.

We can use its extensions for building various web applications on top of the Jakarta EE platform, or we may just use its dependency injection provisions in simple standalone applications.

Q2. What Are the Benefits of Using Spring?

Spring targets to make Jakarta EE development easier. Here are the advantages of using it:

  • Lightweight: there is a slight overhead of using the framework in development
  • Inversion of Control (IoC): Spring container takes care of wiring dependencies of various objects, instead of creating or looking for dependent objects
  • Aspect Oriented Programming (AOP): Spring supports AOP to separate business logic from system services
  • IoC container: it manages Spring Bean life cycle and project specific configurations
  • MVC framework: that is used to create web applications or RESTful web services, capable of returning XML/JSON responses
  • Transaction management: reduces the amount of boiler-plate code in JDBC operations, file uploading, etc., either by using Java annotations or by Spring Bean XML configuration file
  • Exception Handling: Spring provides a convenient API for translating technology-specific exceptions into unchecked exceptions

Q3. What Spring Sub-Projects Do You Know? Describe Them Briefly.

  • Core – a key module that provides fundamental parts of the framework, like IoC or DI
  • JDBC – this module enables a JDBC-abstraction layer that removes the need to do JDBC coding for specific vendor databases
  • ORM integration – provides integration layers for popular object-relational mapping APIs, such as JPA, JDO, and Hibernate
  • Web – a web-oriented integration module, providing multipart file upload, Servlet listeners, and web-oriented application context functionalities
  • MVC framework – a web module implementing the Model View Controller design pattern
  • AOP module – aspect-oriented programming implementation allowing the definition of clean method-interceptors and pointcuts

Q4. What Is Dependency Injection?

Dependency Injection, an aspect of Inversion of Control (IoC), is a general concept stating that you do not create your objects manually but instead describe how they should be created. An IoC container will instantiate required classes if needed.

For more details, please refer here.

Q5. How Can We Inject Beans in Spring?

A few different options exist:

  • Setter Injection
  • Constructor Injection
  • Field Injection

The configuration can be done using XML files or annotations.

For more details, check this article.

Q6. Which Is the Best Way of Injecting Beans and Why?

The recommended approach is to use constructor arguments for mandatory dependencies and setters for optional ones. Constructor injection allows injecting values to immutable fields and makes testing easier.

Q7. What Is the Difference Between Beanfactory and Applicationcontext?

BeanFactory is an interface representing a container that provides and manages bean instances. The default implementation instantiates beans lazily when getBean() is called.

ApplicationContext is an interface representing a container holding all information, metadata, and beans in the application. It also extends the BeanFactory interface but the default implementation instantiates beans eagerly when the application starts. This behavior can be overridden for individual beans.

Q8. What Is a Spring Bean?

The Spring Beans are Java Objects that are initialized by the Spring IoC container.

Q9. What Is the Default Bean Scope in Spring Framework?

By default, a Spring Bean is initialized as a singleton.

Q10. How to Define the Scope of a Bean?

To set Spring Bean’s scope, we can use @Scope annotation or “scope” attribute in XML configuration files. There are five supported scopes:

  • singleton
  • prototype
  • request
  • session
  • global-session

For differences, please refer here.

Q11. Are Singleton Beans Thread-Safe?

No, singleton beans are not thread-safe, as thread safety is about execution, whereas the singleton is a design pattern focusing on creation. Thread safety depends only on the bean implementation itself.

Q12. What Does the Spring Bean Lifecycle Look Like?

First, a Spring bean needs to be instantiated, based on Java or XML bean definition. It may also be required to perform some initialization to get it into a usable state. After that, when the bean is no longer required, it will be removed from the IoC container.

Q13. What Is the Spring Java-Based Configuration?

It’s one of the ways of configuring Spring-based applications in a type-safe manner. It’s an alternative to the XML-based configuration.

Q14. Can We Have Multiple Spring Configuration Files in One Project?

Yes, in large projects, having multiple Spring configurations is recommended to increase maintainability and modularity.

You can load multiple Java-based configuration files:

1
2
3
@Configuration
@Import({MainConfig.class, SchedulerConfig.class})
public class AppConfig {

Or load one XML file that will contain all other configs:

1
ApplicationContext context = new ClassPathXmlApplicationContext("spring-all.xml");

And inside this XML file you’ll have:

1
2
<import resource="main.xml"/>
<import resource="scheduler.xml"/>

Q15. What Is Spring Security?

Spring Security is a separate module of the Spring framework that focuses on providing authentication and authorization methods in Java applications. It also takes care of most of the common security vulnerabilities such as CSRF attacks.

To use Spring Security in web applications, you can get started with a simple annotation: @EnableWebSecurity.

Q16. What Is Spring Boot?

Spring Boot is a project that provides a pre-configured set of frameworks to reduce boilerplate configuration so that you can have a Spring application up and running with the smallest amount of code.

Q17. Name Some of the Design Patterns Used in the Spring Framework?

  • Singleton Pattern: Singleton-scoped beans
  • Factory Pattern: Bean Factory classes
  • Prototype Pattern: Prototype-scoped beans
  • Adapter Pattern: Spring Web and Spring MVC
  • Proxy Pattern: Spring Aspect Oriented Programming support
  • Template Method Pattern: JdbcTemplate, HibernateTemplate, etc.
  • Front Controller: Spring MVC DispatcherServlet
  • Data Access Object: Spring DAO support
  • Model View Controller: Spring MVC

Q18. How Does the Scope Prototype Work?

Scope prototype means that every time you call for an instance of the Bean, Spring will create a new instance and return it. This differs from the default singleton scope, where a single object instance is instantiated once per Spring IoC container.

3. Spring Web MVC

Q19. How to Get *ServletContext* and *ServletConfig* Objects in a Spring Bean?

You can do either by:

  1. Implementing Spring-aware interfaces.
  2. Using @Autowired annotation on those beans:
1
2
3
4
5
@Autowired
ServletContext servletContext;

@Autowired
ServletConfig servletConfig;

Q20. What Is a Controller in Spring Mvc?

Simply put, all the requests processed by the DispatcherServlet are directed to classes annotated with @Controller. Each controller class maps one or more requests to methods that process and execute the requests with provided inputs.

Q21. How Does the @Requestmapping Annotation Work?

The @RequestMapping annotation is used to map web requests to Spring Controller methods. In addition to simple use cases, we can use it for mapping of HTTP headers, binding parts of the URI with @PathVariable, and working with URI parameters and the @RequestParam annotation.

4. Spring Data Access

Q22. What Is Spring Jdbctemplate Class and How to Use It?

The Spring JDBC template is the primary API through which we can access database operations logic that we’re interested in:

  • creation and closing of connections
  • executing statements and stored procedure calls
  • iterating over the ResultSet and returning results

To use it, we’ll need to define the simple configuration of DataSource:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Configuration
@ComponentScan("org.baeldung.jdbc")
public class SpringJdbcConfig {
@Bean
public DataSource mysqlDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/springjdbc");
dataSource.setUsername("guest_user");
dataSource.setPassword("guest_password");

return dataSource;
}
}

Q23. How Would You Enable Transactions in Spring and What Are Their Benefits?

There are two distinct ways to configure Transactions – with annotations or by using Aspect Oriented Programming (AOP) – each with their advantages.

The benefits of using Spring Transactions, according to the official docs, 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

Q24. What Is Spring Dao?

Spring Data Access Object is Spring’s support provided to work with data access technologies like JDBC, Hibernate, and JPA in a consistent and easy way.

5. Spring Aspect-Oriented Programming (AOP)

Q25. What Is Aspect-Oriented Programming?

Aspects enable the modularization of cross-cutting concerns such as transaction management that span multiple types and objects by adding extra behavior to already existing code without modifying affected classes.

Q26. What Are Aspect, Advice, Pointcut, and Joinpoint in Aop?

  • Aspect: a class that implements cross-cutting concerns, such as transaction management
  • Advice\: the methods that get executed when a specific JoinPoint with matching Pointcut is reached in the application
  • Pointcut: a set of regular expressions that are matched with JoinPoint to determine whether Advice needs to be executed or not
  • JoinPoint: a point during the execution of a program, such as the execution of a method or the handling of an exception

Q27. What Is Weaving?

According to the official docs, weaving is a process that links aspects with other application types or objects to create an advised object. This can be done at compile time, load time, or at runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime.

6. Spring 5

Q28. What Is Reactive Programming?

Reactive programming is about non-blocking, event-driven applications that scale with a small number of threads, with back pressure being a key ingredient that aims to ensure producers don’t overwhelm consumers.

The primary benefits of reactive programming are:

  • increased utilization of computing resources on multicore and multi-CPU hardware
  • and increased performance by reducing serialization

Reactive programming is generally event-driven, in contrast to reactive systems, which are message-driven. Thus, using reactive programming does not mean we’re building a reactive system, which is an architectural style.

However, reactive programming may be used as a means to implement reactive systems if we follow the Reactive Manifesto, which is quite vital to understand.

Based on this, reactive systems have four important characteristics:

  • Responsive: the system should respond in a timely manner
  • Resilient: in case the system faces any failure, it should stay responsive
  • Elastic: reactive systems can react to changes and stay responsive under varying workload
  • Message-driven: reactive systems need to establish a boundary between components by relying on asynchronous message passing

Q29. What Is Spring Webflux?

Spring WebFlux is Spring’s reactive-stack web framework, and it’s an alternative to Spring MVC.

Q30. What Are the Mono and Flux Types?

The WebFlux framework in Spring Framework 5 uses Reactor as its async foundation.

This project provides two core types: Mono to represent a single async value, and Flux to represent a stream of async values. They both implement the Publisher interface defined in the Reactive Streams specification.

Mono implements Publisher and returns 0 or 1 elements:

1
public abstract class Mono<T> implements Publisher<T> {...}

Also, Flux implements Publisher and returns N elements:

1
public abstract class Flux<T> implements Publisher<T> {...}

By definition, the two types represent streams, hence they’re both lazy, which means nothing is executed until we consume the stream using the subscribe() method. Both types are immutable, therefore calling any method will return a new instance of Flux or Mono.

Q31. What Is the Use of Webclient and Webtestclient?

WebClient is a component in the new Web Reactive framework that can act as a reactive client for performing non-blocking HTTP requests. Being a reactive client, it can handle reactive streams with back pressure, and it can take full advantage of Java 8 lambdas. It can also handle both sync and async scenarios.

On the other hand, the WebTestClient is a similar class that we can use in tests. Basically, it’s a thin shell around the WebClient. It can connect to any server over an HTTP connection. It can also bind directly to WebFlux applications using mock request and response objects, without the need for an HTTP server.

Q32. What Are the Disadvantages of Using Reactive Streams?

The major disadvantages of using reactive streams are:

  • Troubleshooting a Reactive application is a bit difficult;
  • There is limited support for reactive data stores, as traditional relational data stores have yet to embrace the reactive paradigm
  • There’s an extra learning curve when implementing

Q33. Is Spring 5 Compatible With Older Versions of Java?

In order to take advantage of Java 8 features, the Spring codebase has been revamped. This means older versions of Java cannot be used. Hence, the framework requires a minimum of Java 8.

Q34. How Does Spring 5 Integrate With Jdk 9 Modularity?

In Spring 5, everything has been modularized, thus we won’t be forced to import jars that may not have the functionalities we’re looking for.

Let’s see an example to understand the new module functionality in Java 9 and how to organize a Spring 5 project based on this concept.

To start, let’s create a new class that contains a single method to return a String “HelloWorld”. We’ll place this within a new Java project – HelloWorldModule:

1
2
3
4
5
6
package com.hello;
public class HelloWorld {
public String sayHello(){
return "HelloWorld";
}
}

Then let’s create a new module:

1
2
3
module com.hello {
export com.hello;
}

Now, let’s create a new Java Project, HelloWorldClient, to consume the above module by defining a module:

1
2
3
module com.hello.client {
requires com.hello;
}

The above module will be available for testing now:

1
2
3
4
5
6
public class HelloWorldClient {
public static void main(String[] args) {
HelloWorld helloWorld = new HelloWorld();
log.info(helloWorld.sayHello());
}
}

Q35. Can We Use Both Web Mvc and Webflux in the Same Application?

As of now, Spring Boot will only allow either Spring MVC or Spring WebFlux, as Spring Boot tries to auto-configure the context depending on the dependencies that exist in its classpath.

Also, Spring MVC cannot run on Netty. Moreover, MVC is a blocking paradigm and WebFlux is a non-blocking style, therefore we shouldn’t be mixing both together, as they serve different purposes.

7. Conclusion

In this extensive article, we’ve explored some of the most important questions for a technical interview all about Spring.

We hope that this article will help you in your upcoming Spring interview. Good luck!

The Most Common Behavioral Interview Questions and Answers

Unlike traditional interview questions, behavior job interview techniques look for concrete examples of skills and experiences that relate to the position. Your answers to these questions should provide a brief story that illustrates your skills and strengths as an employee. For each answer, give the interviewer the background to the story briefly, specific actions you took and the results.

Tips for answering behavioral interview questions

Here are some tips you can use as you answer behavioral interview questions:

  • Prepare ahead of time: While you may be asked a few uncommon questions, most interviewers ask many of the same interview questions, which is why it’s helpful to review common behavioral interview questions in advance and practice your responses. This will ensure you have thoughtful anecdotes ready in advance. Another way to feel fully prepared with anecdotes is to think of examples for every responsibility or challenge listed on the job description. Keep in mind that they don’t have to be direct examples. For example, if you’re applying for a manager job but have never been a supervisor, talk about how you were the go-to person on your team for training new employees and were widely known as a problem-solver.
  • Take your time answering: After a question is asked, give yourself a moment to think of an appropriate story before answering. Take a breath, pause or even take a drink of water to calm any nerves before responding.
  • Be positive: While behavioral interview questions require you to think of a failure or problem at work, don’t focus on that part of your story. Describe the background enough so that the interviewer understands the situation and then quickly move on to how you solved the problem and the results you achieved.
  • Follow the STAR method: Use the STAR method to answer any question. STAR stands for situation, task, action and result. For Situation, briefly share context and relevant details for the challenge or problem you were facing. For Task, describe your role in overcoming the challenge or handling the situation. For Action, explain what action was taken by you or your team, although it’s important to focus on the role you played, specifically. For Result, share the successful outcome. If possible, provide quantifiable results or concrete examples of the effect of your effort.

Sample interview questions and answers

Here are some common behavioral interview questions and suggestions for how to answer them. Remember that the interviewer is trying to gauge not only how successfully you solved problems but also the strategies and skills you used to do so.

  1. Tell me about a time when you handled a challenging situation.
  2. Tell me about a time when you made a mistake. What did you do to correct it?
  3. Tell me about a time when you were in conflict with a peer and how the situation was resolved.
  4. Tell me about how you work under pressure.
  5. Give me an example of how you set goals.
  6. Give me an example of a time you made a decision that was unpopular and explain how you handled implementing it.
  7. Share an example of how you were able to motivate a coworker, your peers or your team.
  8. Tell me about a goal you set and reached and how you achieved it.
  9. Tell me about the last time your workday ended before you were able to get everything done.
  10. Tell me about a goal you failed to achieve.

1. Tell me about a time when you handled a challenging situation.

With this question, the interviewer wants to see how you handle challenging situations when they arise. A great example is one where you successfully problem-solved to overcome the challenge. It could also be an example of a time you made mistakes in handling the challenge but learned from the experience and know what you would do differently next time.

Example: *”*My manager left town unexpectedly when we in the middle of pitching large sponsors for an upcoming conference. I was tasked with putting together the slide decks for the presentations to secure these sponsors but all I had was a few notes left behind by my manager. Because he was unavailable, I called a meeting with members of our team and we generated a list of the biggest selling points that would be most impactful with potential sponsors. After creating the slide deck, I presented the presentation successfully and we got the sponsorship. I’m incredibly proud of the results we achieved when we worked together.”

2. Tell me about a time when you made a mistake. What did you do to correct it?

The interviewer understands that everyone makes mistakes. What they want to know, with this question, is how you handle mistakes. A great response to this question is one in which you take full responsibility for the mistake, worked hard to correct it and took steps to minimize the likelihood that it would happen again.

Example: “When I was working at a printing company, I misquoted the fees for a particular job. I realized the mistake, I went directly to my manager and explained what happened. He said he appreciated my honesty and suggested that we waive the setup fee for the job as an apology to the customer. I spoke to the customer directly and explained what happened and that the quoted price was actually higher than my original estimate, but that we would be happy to waive the setup fee. The customer understood and appreciated the effort to make the situation right. After that happened, I printed our price sheet to have it quickly at hand and implemented a new process for quoting estimates, one in which I double-check the final estimate before sending it.”*

3. Tell me about a time when you were in conflict with a peer and how the situation was resolved.

In workplaces where there are a large number of people with different personality types and communication styles, conflicts can occur. The interviewer wants to see, with this question, how you handle conflicts in the workplace and what your conflict resolution strategy is. A great answer is one where you demonstrate a specific strategy that you used to resolve a problem and find a mutually agreeable resolution.

Example: *”I had a sales manager who was great about stepping in to help when members of our team were struggling with meeting goals. However, she had a single approach that didn’t work for everyone and members of our team were getting frustrated and felt they were being micro-managed. I suggested that I sit down one-on-one with our manager, having heard the frustrations of the team. I avoided us all sitting down because I didn’t want her to feel ganged up on and become defensive. After talking, we decided that she would let team members know her door was open if they needed help but that she would let them be in charge of the strategy they used to meet their goals. We also implemented a monthly, optional training program where we had different team members present what was working for them in order to offer a variety of approaches.”*

4. Tell me about how you work under pressure.

The interviewer is using this question to see how well you work under pressure and what strategies you have used in the past to handle the pressure. This question is especially important if you’re interviewing for a high-stress job. A great answer will give a specific example of how you managed a high-pressure situation successfully. It could also include what you would have done differently, looking back.

Example: *”I had been working on a large project that my team committed to turning around for the client in 60 days. My manager came to me and said that the client wanted it back in 45 days and that we would need to speed up our work without losing momentum on our other projects. I met with our team and we reviewed the calendar. We eliminated team meetings and shifted lower-priority tasks until the end of the 45-day period to add extra hours to our workweeks. I challenged my team to complete the project in 45 days or left and as a reward promised two days of extra PTO time. Our team got the job done in 42 days.”*

5. Give me an example of how you set goals.

This question is designed to show the interviewer how well you plan and set goals. A great answer is one where you discuss an ambitious goal you set for yourself and how you came up with a plan for success.

Example: *”Within a few weeks of beginning my job as a server at a restaurant, I knew I wanted to work in the foodservice industry as a chef. I decided I would learn all I could in my current position until an opening became available in the kitchen, even for less pay. I wanted the experience of working in a restaurant kitchen environment. I also started saving up money at that time to go to the culinary academy. I knew that by the time I finished school, I would have been working in the kitchen for a number of years and would be highly competitive as a candidate for chef roles.”*

6. Give me an example of a time you made a decision that was unpopular and explain how you handled implementing it.

Managers sometimes have to make difficult decisions that aren’t popular with all employees. The interviewer wants to know how you handle this situation and how you implemented the new policy or plan. A great answer is one where you show you moved forward with the decision but communicated your reasoning to garner the support of more of the employees.

Example: *”I took over management of a gym where the trainers were allowed to cover one another’s shifts without the knowledge or approval of management. I didn’t like the uncertainty involved, because if someone failed to show up for a class, there was no way to know which trainerwas supposed to be there. I implemented a new policy that required trainers to go through management to make schedule changes. I also explained the problem with the previous approach and how this would resolve any possible issues.”*

7. Share an example of how you were able to motivate a coworker, your peers or your team.

With this question, the interviewer is evaluating your ability and willingness to lead, even informally. A great answer is one that shows you provided encouragement and offered help in some way. This could mean you offered to help with some work if they’ve fallen behind or that you suggested helping them with strategies to move through their work more quickly and efficiently.

Example: *”I noticed that one of my coworkers was having a hard time meeting her sales quotas each month. I told her that not every sales technique works for every personality and that it can take time to figure out what will work best for her. I suggested we find time over the next day or two and I would show her some techniques I was using that I found highly effective. And it worked! After a couple of weeks of practice and trial and error, she was consistently hitting her quota.”*

8. Tell me about a goal you set and reached and how you achieved it.

For this question, the interviewer wants to see how you plan to achieve a goal. A good answer is one where you were given a goal, created a plan and followed the necessary steps to achieve it. A great answer is one where you set your own goal, especially a large goal, and took the necessary steps to reach it.

Example: “

9. Tell me about the last time your workday ended before you were able to get everything done.

This question is designed to evaluate your commitment, work ethic, prioritization skills and ability to communicate. While the interviewer doesn’t expect heroic efforts daily, they do want to see a level of dedication to getting your job done. A great answer is that you either stayed late to finish your work, came in early the next day or prioritized differently. It’s also important to emphasize that you communicated to others that you might miss a deadline in case changes need to be made or clients need to be contacted.

Example: *”We had a client wanted us to deliver new social media content to them by Wednesday of each week to get it scheduled for the following week. One week they requested double the content in order to increase their online activity in advance of a big launch. I decided to stay late the night before the deliverable was due. I also let the manager know that we might be a few hours behind for our content that week. A coworker and I went in early the next morning, together, made our deadline.”*

10. Tell me about a goal you failed to achieve.

With this question, the interviewer is evaluating how you handle disappointment and failure. They also want to see how you decide when it’s time to give up, accept that something didn’t work and move forward. A great response is one where you set a huge goal, didn’t achieve it, took responsibility and learned from the experience. Some examples of things you could learn from it are what you would do differently next time, something about yourself, what motivates you or what is truly important to you.

Example: *”I was working on a start-up where our goal was to create content that would educate parents about why it’s important to spend time as a family around the dinner table. Unfortunately, we were never able to figure out a way to monetize the business. We polled our audience and tried many different ideas, but after a year we had to move on. However, I learned so much from the process. I developed numerous skills and realized I’m incredibly good at shifting direction when something isn’t working. I realized I don’t let defeats discourage me for long. Each time something didn’t work, I picked myself back up and moved forward.”*

The Standard of Code Review

The primary purpose of code review is to make sure that the overall code health of Google’s code base is improving over time. All of the tools and processes of code review are designed to this end.

In order to accomplish this, a series of trade-offs have to be balanced.

First, developers must be able to make progress on their tasks. If you never submit an improvement to the codebase, then the codebase never improves. Also, if a reviewer makes it very difficult for any change to go in, then developers are disincentivized to make improvements in the future.

On the other hand, it is the duty of the reviewer to make sure that each CL is of such a quality that the overall code health of their codebase is not decreasing as time goes on. This can be tricky, because often, codebases degrade through small decreases in code health over time, especially when a team is under significant time constraints and they feel that they have to take shortcuts in order to accomplish their goals.

Also, a reviewer has ownership and responsibility over the code they are reviewing. They want to ensure that the codebase stays consistent, maintainable, and all of the other things mentioned in “What to look for in a code review.”

Thus, we get the following rule as the standard we expect in code reviews:

In general, reviewers should favor approving a CL once it is in a state where it definitely improves the overall code health of the system being worked on, even if the CL isn’t perfect.

That is the senior principle among all of the code review guidelines.

There are limitations to this, of course. For example, if a CL adds a feature that the reviewer doesn’t want in their system, then the reviewer can certainly deny approval even if the code is well-designed.

A key point here is that there is no such thing as “perfect” code—there is only better code. Reviewers should not require the author to polish every tiny piece of a CL before granting approval. Rather, the reviewer should balance out the need to make forward progress compared to the importance of the changes they are suggesting. Instead of seeking perfection, what a reviewer should seek is continuous improvement. A CL that, as a whole, improves the maintainability, readability, and understandability of the system shouldn’t be delayed for days or weeks because it isn’t “perfect.”

Reviewers should always feel free to leave comments expressing that something could be better, but if it’s not very important, prefix it with something like “Nit: “ to let the author know that it’s just a point of polish that they could choose to ignore.

Note: Nothing in this document justifies checking in CLs that definitely worsen the overall code health of the system. The only time you would do that would be in an emergency.

Mentoring

Code review can have an important function of teaching developers something new about a language, a framework, or general software design principles. It’s always fine to leave comments that help a developer learn something new. Sharing knowledge is part of improving the code health of a system over time. Just keep in mind that if your comment is purely educational, but not critical to meeting the standards described in this document, prefix it with “Nit: “ or otherwise indicate that it’s not mandatory for the author to resolve it in this CL.

Principles

  • Technical facts and data overrule opinions and personal preferences.
  • On matters of style, the style guide is the absolute authority. Any purely style point (whitespace, etc.) that is not in the style guide is a matter of personal preference. The style should be consistent with what is there. If there is no previous style, accept the author’s.
  • Aspects of software design are almost never a pure style issue or just a personal preference. They are based on underlying principles and should be weighed on those principles, not simply by personal opinion. Sometimes there are a few valid options. If the author can demonstrate (either through data or based on solid engineering principles) that several approaches are equally valid, then the reviewer should accept the preference of the author. Otherwise the choice is dictated by standard principles of software design.
  • If no other rule applies, then the reviewer may ask the author to be consistent with what is in the current codebase, as long as that doesn’t worsen the overall code health of the system.

Resolving Conflicts

In any conflict on a code review, the first step should always be for the developer and reviewer to try to come to consensus, based on the contents of this document and the other documents in The CL Author’s Guide and this Reviewer Guide.

When coming to consensus becomes especially difficult, it can help to have a face-to-face meeting or a video conference between the reviewer and the author, instead of just trying to resolve the conflict through code review comments. (If you do this, though, make sure to record the results of the discussion as a comment on the CL, for future readers.)

If that doesn’t resolve the situation, the most common way to resolve it would be to escalate. Often the escalation path is to a broader team discussion, having a Technical Lead weigh in, asking for a decision from a maintainer of the code, or asking an Eng Manager to help out. Don’t let a CL sit around because the author and the reviewer can’t come to an agreement.

General Questions – Spring Interview Questions

1. What are the major features in different versions of Spring Framework?

Version Feature
Spring 2.5 This version was released in 2007. It was the first version which supported annotations.
Spring 3.0 This version was released in 2009. It made full-fledged use of improvements in Java5 and also provided support to JEE6.
Spring 4.0 This version was released in 2013. This was the first version to provide full support to Java 8.

2. What is a Spring Framework?

  • Spring is a powerful open source, application framework created to reduce the complexity of enterprise application development.
  • It is light-weighted and loosely coupled.
  • It has layered architecture, which allows you to select the components to use, while also providing a cohesive framework for J2EE application development.
  • Spring framework is also called the framework of frameworks as it provides support to various other frameworks such as Struts, Hibernate, Tapestry, EJB, JSF etc.

3. List the advantages of Spring Framework.

  • Because of Spring Frameworks layered architecture, you can use what you need and leave which you don’t.
  • Spring Framework enables POJO (Plain Old Java Object) Programming which in turn enables continuous integration and testability.
  • JDBC is simplified due to Dependency Injection and Inversion of Control.
  • It is open-source and has no vendor lock-in.

4. What are the different features of Spring Framework?

Following are some of the major features of Spring Framework :

  • Lightweight: Spring is lightweight when it comes to size and transparency.
  • Inversion of control (IOC): The objects give their dependencies instead of creating or looking for dependent objects. This is called Inversion Of Control.
  • Aspect oriented Programming (AOP): Aspect oriented programming in Spring supports cohesive development by separating application business logic from system services.
  • Container: Spring Framework creates and manages the life cycle and configuration of the application objects.
  • MVC Framework: Spring Framework’s MVC web application framework is highly configurable. Other frameworks can also be used easily instead of Spring MVC Framework.
  • Transaction Management: Generic abstraction layer for transaction management is provided by the Spring Framework. Spring’s transaction support can be also used in container less environments.
  • JDBC Exception Handling: The JDBC abstraction layer of the Spring offers an exception hierarchy, which simplifies the error handling strategy.

5. How many modules are there in Spring Framework and what are they?

There are around 20 modules which are generalized into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation and Test.

  • Spring Core Container – This layer is basically the core of Spring Framework. It contains the following modules :
  1. Spring Core
  2. Spring Bean
  3. SpEL (Spring Expression Language)
  4. Spring Context
  • Data Access/Integration – This layer provides support to interact with the database. It contains the following modules :
  1. JDBC (Java DataBase Connectivity)
  2. ORM (Object Relational Mapping)
  3. OXM (Object XML Mappers)
  4. JMS (Java Messaging Service)
  5. Transaction
  • Web – This layer provides support to create web application. It contains the following modules :
  1. Web
  2. Web – MVC
  3. Web – Socket
  4. Web – Portlet
  • Aspect Oriented Programming (AOP) – In this layer you can use Advices, Pointcuts etc., to decouple the code.
  • Instrumentation – This layer provides support to class instrumentation and classloader implementations.
  • Test – This layer provides support to testing with JUnit and TestNG.

Few Miscellaneous modules are given below:

  • Messaging – This module provides support for STOMP. It also supports an annotation programming model that is used for routing and processing STOMP messages from WebSocket clients.
  • Aspects – This module provides support to integration with AspectJ.

6. What is a Spring configuration file?

A Spring configuration file is an XML file. This file mainly contains the classes information. It describes how those classes are configured as well as introduced to each other. The XML configuration files, however, are verbose and more clean. If it’s not planned and written correctly, it becomes very difficult to manage in big projects.

7. What are the different components of a Spring application?

A Spring application, generally consists of following components:

  • Interface: It defines the functions.
  • Bean class: It contains properties, its setter and getter methods, functions etc.
  • Spring Aspect Oriented Programming (AOP): Provides the functionality of cross-cutting concerns.
  • Bean Configuration File: Contains the information of classes and how to configure them.
  • User program: It uses the function.

8. What are the various ways of using Spring Framework?

Spring Framework can be used in various ways. They are listed as follows:

  1. As a Full-fledged Spring web application.
  2. As a third-party web framework, using Spring Frameworks middle-tier.
  3. For remote usage.
  4. As Enterprise Java Bean which can wrap existing POJOs (Plain Old Java Objects).

Dependency Injection/ IoC Container – Spring Interview Questions

9. What is Spring IOC Container?

At the core of the Spring Framework, lies the Spring container. The container creates the object, wires them together, configures them and manages their complete life cycle. The Spring container makes use of Dependency Injection to manage the components that make up an application. The container receives instructions for which objects to instantiate, configure, and assemble by reading the configuration metadata provided. This metadata can be provided either by XML, Java annotations or Java code.

10. What do you mean by Dependency Injection?

In Dependency Injection, you do not have to create your objects but have to describe how they should be created. You don’t connect your components and services together in the code directly, but describe which services are needed by which components in the configuration file. The IoC container will wire them up together.

11. In how many ways can Dependency Injection be done?

In general, dependency injection can be done in three ways, namely :

  • Constructor Injection
  • Setter Injection
  • Interface Injection

In Spring Framework, only constructor and setter injections are used.

12. Differentiate between constructor injection and setter injection.

Constructor Injection vs Setter Injection

Constructor Injection Setter Injection
There is no partial injection. There can be partial injection.
It doesn’t override the setter property. It overrides the constructor property.
It will create a new instance if any modification is done. It will not create new instance if any modification is done.
It works better for many properties. It works better for few properties.

13. How many types of IOC containers are there in spring?

  1. BeanFactory: BeanFactory is like a factory class that contains a collection of beans. It instantiates the bean whenever asked for by clients.
  2. ApplicationContext: The ApplicationContext interface is built on top of the BeanFactory interface. It provides some extra functionality on top BeanFactory.

14. Differentiate between BeanFactory and ApplicationContext.

BeanFactory vs ApplicationContext

BeanFactory ApplicationContext
It is an interface defined in org.springframework.beans.factory.BeanFactory It is an interface defined in org.springframework.context.ApplicationContext
It uses Lazy initialization It uses Eager/ Aggressive initialization
It explicitly provides a resource object using the syntax It creates and manages resource objects on its own
It doesn’t supports internationalization It supports internationalization
It doesn’t supports annotation based dependency It supports annotation based dependency

15. List some of the benefits of IoC.

Some of the benefits of IoC are:

  • It will minimize the amount of code in your application.
  • It will make your application easy to test because it doesn’t require any singletons or JNDI lookup mechanisms in your unit test cases.
  • It promotes loose coupling with minimal effort and least intrusive mechanism.
  • It supports eager instantiation and lazy loading of the services.

Spring Beans – Spring Interview Questions

16. Explain Spring Beans?

  • They are the objects that form the backbone of the user’s application.
  • Beans are managed by the Spring IoC container.
  • They are instantiated, configured, wired and managed by a Spring IoC container
  • Beans are created with the configuration metadata that the users supply to the container.

17. How configuration metadata is provided to the Spring container?

Configuration metadata can be provided to Spring container in following ways:

  • XML-Based configuration: In Spring Framework, the dependencies and the services needed by beans are specified in configuration files which are in XML format. These configuration files usually contain a lot of bean definitions and application specific configuration options. They generally start with a bean tag.

  • Annotation-Based configuration: Instead of using XML to describe a bean wiring, you can configure the bean into the component class itself by using annotations on the relevant class, method, or field declaration. By default, annotation wiring is not turned on in the Spring container. So, you need to enable it in your Spring configuration file before using it.

  • Java-based configuration: The key features in Spring Framework’s new Java-configuration support are @Configuration annotated classes and @Bean annotated methods.

  1. @Bean annotation plays the same role as the element.
  2. 2.@Configuration classes allows to define inter-bean dependencies by simply calling other @Bean methods in the same class.

18. How many bean scopes are supported by Spring?

The Spring Framework supports five scopes. They are:

  • Singleton: This provides scope for the bean definition to single instance per Spring IoC container.
  • Prototype: This provides scope for a single bean definition to have any number of object instances.
  • Request: This provides scope for a bean definition to an HTTP-request.
  • Session: This provides scope for a bean definition to an HTTP-session.
  • Global-session: This provides scope for a bean definition to an Global HTTP-session.

The last three are available only if the users use a web-aware ApplicationContext.

19. What is the Bean life cycle in Spring Bean Factory Container?

Bean life cycle in Spring Bean Factory Container is as follows:

  1. The Spring container instantiates the bean from the bean’s definition in the XML file.
  2. Spring populates all of the properties using the dependency injection, as specified in the bean definition.
  3. The factory calls setBeanName() by passing the bean’s ID, if the bean implements the BeanNameAware interface.
  4. The factory calls setBeanFactory() by passing an instance of itself, if the bean implements the BeanFactoryAware interface.
  5. preProcessBeforeInitialization() methods are called if there are any BeanPostProcessors associated with the bean.
  6. If an init-method is specified for the bean, then it will be called.
  7. Finally, postProcessAfterInitialization() methods will be called if there are any BeanPostProcessors associated with the bean.

20. Explain inner beans in Spring.

A bean can be declared as an inner bean only when it is used as a property of another bean. For defining a bean, the Spring’s XML based configuration metadata provides the use of element inside the or . Inner beans are always anonymous and they are always scoped as prototypes. For example, let’s say we have one Student class having reference of Person class. Here we will be creating only one instance of Person class and use it inside Student.

21. Define Bean Wiring.

When beans are combined together within the Spring container, it’s called wiring or bean wiring. The Spring container needs to know what beans are needed and how the container should use dependency injection to tie the beans together, while wiring beans.

22. What do you understand by auto wiring and name the different modes of it?

The Spring container is able to autowire relationships between the collaborating beans. That is, it is possible to let Spring resolve collaborators for your bean automatically by inspecting the contents of the BeanFactory.
Different modes of bean auto-wiring are:

  1. no: This is default setting which means no autowiring. Explicit bean reference should be used for wiring.
  2. byName: It injects the object dependency according to name of the bean. It matches and wires its properties with the beans defined by the same names in the XML file.
  3. byType: It injects the object dependency according to type. It matches and wires a property if its type matches with exactly one of the beans name in XML file.
  4. constructor: It injects the dependency by calling the constructor of the class. It has a large number of parameters.
  5. autodetect: First the container tries to wire using autowire by constructor, if it can’t then it tries to autowire by byType.

23. What are the limitations with auto wiring?

Following are some of the limitations you might face with auto wiring:

  • Overriding possibility: You can always specify dependencies using and settings which will override autowiring.
  • Primitive data type: Simple properties such as primitives, Strings and Classes can’t be autowired.
  • Confusing nature: Always prefer using explicit wiring because autowiring is less precise.

Spring Annotations – Spring Interview Questions

24. What do you mean by Annotation-based container configuration?

Instead of using XML to describe a bean wiring, the developer moves the configuration into the component class itself by using annotations on the relevant class, method, or field declaration. It acts as an alternative to XML setups. For example:

1
2
3
4
5
6
7
@Configuration
public class AnnotationConfig
{
@Bean
public MyDemo myDemo()
{ return new MyDemoImpll(); }
}

25. How annotation wiring can be turned on in Spring?

By default, Annotation wiring is not turned on in the Spring container. Thus, to use annotation based wiring we must enable it in our Spring configuration file by configuring <context:annotation-config> element. For example:

1
2
3
4
<beans xmlns="<a href="http://www.springframework.org/schema/beans">http://www.springframework.org/schema/beans</a>" xmlns:xsi="<a href="http://www.w3.org/2001/XMLSchema-instance">http://www.w3.org/2001/XMLSchema-instance</a>" xmlns:context="<a href="http://www.springframework.org/schema/context">http://www.springframework.org/schema/context</a>">
<context:annotation-config/>
<beans ………… />
</beans>

26. What’s the difference between @Component, @Controller, @Repository & @Service annotations in Spring?

@Component: This marks a java class as a bean. It is a generic stereotype for any Spring-managed component. The component-scanning mechanism of spring now can pick it up and pull it into the application context.

@Controller: This marks a class as a Spring Web MVC controller. Beans marked with it are automatically imported into the Dependency Injection container.

@Service: This annotation is a specialization of the component annotation. It doesn’t provide any additional behavior over the @Component annotation. You can use @Service over @Component in service-layer classes as it specifies intent in a better way.

@Repository: This annotation is a specialization of the @Component annotation with similar use and functionality. It provides additional benefits specifically for DAOs. It imports the DAOs into the DI container and makes the unchecked exceptions eligible for translation into Spring DataAccessException.

27. What do you understand by @Required annotation?

@Required is applied to bean property setter methods. This annotation simply indicates that the affected bean property must be populated at the configuration time with the help of an explicit property value in a bean definition or with autowiring. If the affected bean property has not been populated, the container will throw BeanInitializationException.

1
2
3
4
5
6
7
8
9
public class Employee
{
private String name;
@Required
public void setName(String name)
{this.name=name; }
public string getName()
{ return name; }
}

28. What do you understand by @Autowired annotation?

The @**Autowired** annotation provides more accurate control over where and how autowiring should be done. This annotation is used to autowire bean on the setter methods, constructor, a property or methods with arbitrary names or multiple arguments. By default, it is a type driven injection.

1
2
3
4
5
6
7
8
9
public class Employee
{
private String name;
@Autowired
public void setName(String name)
{this.name=name; }
public string getName()
{ return name; }
}

29. What do you understand by @Qualifier annotation?

When you create more than one bean of the same type and want to wire only one of them with a property you can use the @Qualifier annotation along with @**Autowired** to remove the ambiguity by specifying which exact bean should be wired.

For example, here we have two classes, Employee and EmpAccount respectively. In EmpAccount, using @Qualifier its specified that bean with id emp1 must be wired.

Employee.java

1
2
3
4
5
6
7
8
9
public class Employee
{
private String name;
@Autowired
public void setName(String name)
{ this.name=name; }
public string getName()
{ return name; }
}

EmpAccount.java

1
2
3
4
5
6
7
8
9
10
public class EmpAccount
{
private Employee emp;
@Autowired
@Qualifier(emp1)
public void showName()
{
System.out.println(“Employee name : ”+emp.getName);
}
}

30. What do you understand by @RequestMapping annotation?

@RequestMapping annotation is used for mapping a particular HTTP request method to a specific class/ method in controller that will be handling the respective request. This annotation can be applied at both levels:

  • Class level : Maps the URL of the request
  • Method level: Maps the URL as well as HTTP request method

Data Access – Spring Interview Questions

31. Describe Spring DAO support?

The Data Access Object (DAO) support in Spring makes it easy to work with data access technologies like JDBC, Hibernate or JDO in a consistent way. This allows one to switch between the persistence technologies easily. It also allows you to code without worrying about catching exceptions that are specific to each of these technology.

32. Name the exceptions thrown by the Spring DAO classes.

See the below diagram, it depicts all the Spring DAO classes in the hierarchical order.

33. Which classes are present in spring JDBC API?

Classes present in JDBC API are as follows:

  1. JdbcTemplate
  2. SimpleJdbcTemplate
  3. NamedParameterJdbcTemplate
  4. SimpleJdbcInsert
  5. SimpleJdbcCall

34. What are the ways by which Hibernate can be accessed using Spring?

There are two ways by which we can access Hibernate using Spring:

  1. Inversion of Control with a Hibernate Template and Callback
  2. Extending HibernateDAOSupport and Applying an AOP Interceptor node

35. Name the types of transaction management that Spring supports.

Two types of transaction management are supported by Spring. They are:

  1. Programmatic transaction management: In this, the transaction is managed with the help of programming. It provides you extreme flexibility, but it is very difficult to maintain.
  2. Declarative transaction management: In this, the transaction management is separated from the business code. Only annotations or XML based configurations are used to manage the transactions.

36. What are the different ORM’s supported by Spring?

JPA, Hibernate, IBatis, OJB, Oracle

Aspect Oriented Programming (AOP) – Spring Interview Questions

37. Describe AOP.

Aspect-oriented programming or AOP is a programming technique which allows programmers to modularize crosscutting concerns or behavior that cuts across the typical divisions of responsibility. Examples of cross-cutting concerns can be logging and transaction management. The core of AOP is an aspect. It encapsulates behaviors that can affect multiple classes into reusable modules.

38. What do you mean by Aspect?

Aspect is a modularization of concern which cuts across multiple objects. Transaction management is a good example of a crosscutting concern in J2EE applications. Aspects are implemented using regular classes or regular classes annotated with the @Aspect annotation in Spring Framework.

39. Explain JoinPoint.

A point during the execution of a program is called JoinPoint, such as the execution of a method or the handling of an exception. In Spring AOP, a joinpoint always represents a method execution.

40. What is an Advice?

An Action taken by an aspect at a particular joinpoint is known as an Advice. Spring AOP uses an advice as an interceptor, maintaining a chain of interceptors “around” the join point.

41. What are the different types of Advices?

Different types of Advices in Spring AOP are:

  1. Before: These types of advices execute before the joinpoint methods and are configured using @Before annotation mark.
  2. After returning: These types of advices execute after the joinpoint methods completes executing normally and are configured using @AfterReturning annotation mark.
  3. After throwing: These types of advices execute only if joinpoint method exits by throwing an exception and are configured using @AfterThrowing annotation mark.
  4. After (finally): These types of advices execute after a joinpoint method, regardless of the method’s exit whether normally or exceptional return and are configured using @After annotation mark.
  5. Around: These types of advices execute before and after a joinpoint and are configured using @Around annotation mark.

42. Point out the difference between concern and cross-cutting concern in Spring AOP?

The concern is the behavior we want to have in a particular module of an application. It can be defined as a functionality we want to implement.

The cross-cutting concern is a concern which is applicable throughout the application. This affects the entire application. For example, logging, security and data transfer are the concerns needed in almost every module of an application, thus they are the cross-cutting concerns.

43. What are the different AOP implementations?

Spring AOP, Apache AspectJ, JBoss AOP

44. What are the difference between Spring AOP and AspectJ AOP?

Spring AOP vs AspectJ AOP

Spring AOP AspectJ AOP
Runtime weaving through proxy is done Compile time weaving through AspectJ Java tools is done
It supports only method level PointCut It suports field level Pointcuts
It is DTD based It is schema based and Annotation configuration

45. What do you mean by Proxy in Spring Framework?

An object which is created after applying advice to a target object is known as a Proxy. In case of client objects the target object and the proxy object are the same.

Advice + Target Object = Proxy

46. In Spring, what is Weaving?

The process of linking an aspect with other application types or objects to create an advised object is called Weaving. In Spring AOP, weaving is performed at runtime.

MVC (Model-View-Controller) – Spring Interview Questions

47. What do you mean by Spring MVC framework?

The Spring web MVC framework provides model-view-controller architecture and ready to use components that are used to develop flexible and loosely coupled web applications. The MVC pattern helps in separating the different aspects of the application like input logic, business logic and UI logic, while providing a loose coupling between all these elements.

48. Describe DispatcherServlet.

The DispatcherServlet is the core of Spring Web MVC framework. It handles all the HTTP requests and responses. The DispatcherServlet receives the entry of handler mapping from the configuration file and forwards the request to the controller. The controller then returns an object of Model And View. The DispatcherServlet checks the entry of view resolver in the configuration file and calls the specified view component.

49. Explain WebApplicationContext.

The WebApplicationContext is an extension of the plain ApplicationContext. It has some extra features that are necessary for web applications. It differs from a normal ApplicationContext in terms of its capability of resolving themes and in deciding which servlet it is associated with.

50. In Spring MVC framework, what is controller?

Controllers provide access to the application behavior. These behaviors are generally defined through a service interface. Controllers interpret the user input and transform it into a model which is represented to the user by the view. In Spring, controller is implemented in a very abstract way. It also enables you to create a wide variety of controllers.

俗话说“工欲善其事,必先利其器”,今天我们来说说和开发工具有关的话题。由于开发过程中会用到的工具多种多样,根据“二八原理”,我只挑选和开发最密切相关的少数几种工具来聊一聊。

★编辑器

编辑器显然是用的最频繁的工具了(尤其是对于经常写代码的人),但是很大一部分人不善于使用编辑器。因此我先来说一下对编辑器使用的一些体会。顺便提一下,如果你连盲打都没过关,请先去学打字,再回来看这个帖子。

◇字体

  对于写代码而言,字体的选择是非常重要的(看起来舒服的字体起码能保护眼睛)。首先必须选择一种【等宽】的字体(比如 FixedSys、Courier New);其次该字体必须能够【清楚地区分】如下几种容易混淆的字符,避免阅读代码的时候看错:

数字0 和 字母O
数字1 和 大写字母I 和 小写字母l 和 或运算符|
数字2 和 字母z
数字9 和 小写字母q
乘号* 和 字母X
分号; 和 冒号:

◇颜色

  你使用的编辑器必须支持【自定义】的词法高亮(词法着色)。
  对词法高亮进行设置时,至少要把:“代码注释、关键字、字符串、数字”这几种语法要素用不同的颜色区分开。当然,如果还能根据“类名、函数名、变量名等”进行着色,那就更好了。

◇快捷键

  熟练地使用快捷键能大大提高编辑的效率。因为你的手不需要离开键盘去操纵鼠标。而且当编辑的文本比较大时,有些编辑命令即使用鼠标操作也挺费劲(比如全选、移动到文件尾),不如快捷键方便。
  所以,你使用的编辑器必须支持快捷键(这个大多数都能做到),而且还必须支持编辑命令和快捷键的绑定(也就是自己设置某个编辑命令对应的快捷键),便于根据个人喜好设置快捷键。

◇其它功能

还有一些比较琐碎的功能,比如:代码自动缩进、自动补全、动态提示等等。最后,如果你需要经常在不同的操作系统上进行工作,那你的编辑器还必须得支持跨平台才行。
虽然说了这么多条条框框,但是符合全部要求的软件并不难找,比如EmacsVIMEclipse等软件都可以满足上述的编辑功能,具体选哪个就看各自的偏爱了。

★源代码管理工具(版本管理软件)

  为了打字方便,以下简称“RCS”(Revision Control System)。
  通过 RCS 的使用状况,可以看出一个开发团队在软件工程方面的成熟度,因此我们接下来要说说 RCS 的问题。如果你所在的开发团队从来不使用 RCS 进行代码的版本控制,那俺建议你赶紧考虑跳槽。
  据俺多年的观察,发觉 RCS 主要有如下几种误用的情况:

◇不正确的提交频度

  有很多新手不习惯使用 RCS,很少进行代码的提交。有些人甚至到项目快结束时还没有提交过一行代码。结果导致整个 RCS 形同虚设。
  还有一些人则走向另一个极端,频繁提交代码。有些人每改完一个文件就提交一次,还有些人甚至把修改一半,尚【不能】编译通过的代码也提交到 RCS。
  俺个人认为,正确的提交频度应该分两种情况:在编写功能代码时,每完成一个功能点,并且自己经过了自测之后,提交一次;在调试的时候,每修复一个 bug,提交一次。这样能够保证提交到 RCS 的代码都是【能编译通过】的,并且业务逻辑上也是相对完整的(对于每日构建后的测试很重要)。

◇提交时不写注释

  很多人提交代码时不写注释,将来再想到版本历史里面找代码就犹如大海捞针般困难。
  比如在俺经手的代码中,有些源代码文件历时3年,提交次数上百次,如果提交时不写注释,日后根本没法找。

◇不做代码基线(Baseline)、不做代码分支(Branch)

  在正规的开发团队,每当有一个版本发布(Release)并交付给用户使用时,都需要在 RCS 中制作一个基线,以便于进行相应的 bug 跟踪和补丁制作。因此,诸如【做基线】之类的事情,属于整个团队的集体行为,需要由 Team Leader 牵头来搞。
  假如一个开发团队从来不做代码基线或者代码分支,仅仅是把 RCS 当成一个源文件的备份工具来用,那至少说明这个团队的 Team Leader 在软件工程管理方面非常失败。

★用于调试/测试的运行辅助工具

  运行辅助工具对于开发效率的影响也很大。一般来说,你自己的开发机器上要有尽可能仿真(和用户的环境相似)的运行环境,并且运行辅助工具能够有效地发现运行时的一些不正常的信息。这样有利于让 bug 在交付给用户之前【尽早暴露】出来。
  如果你是 Web 开发人员,那么你自己肯定要安装好常用的浏览器(至少包括 IE、Firefox、Chrome)。对于 IE,还得设置成“显示脚本错误通知”。
  如果你主要开发 Windows 应用程序,你手头肯定要备好诸如:Depends(Visual C++自带)、Process Explorer等工具,便于查看进程、线程、动态库、堆内存等运行时信息。
  如果你是搞手机应用的,那么你至少得有目标系统的模拟器软件(如果能配一个真机当然更好)。
  如果你主要进行跨平台方面的开发,那么诸如“VMware / VirtualBox”之类的虚拟化软件是必不可少滴

In less than a decade, two new programming languages have emerged as major options for enterprise development: Go, which was created at Google, and Rust, which was created at Mozilla.

Both languages offer indispensable features for modern software development: a sophisticated and integrated toolchain, memory safety, an open source development model, and strong communities of users.

Apart from those similarities, Rust and Go are dramatically different. They were built to scratch different itches, fulfill different demands, and write different kinds of programs.

Thus, comparing Rust and Go isn’t about which language is “objectively better,” but about which language is best for a given programming task. With that in mind, let’s look at the main ways Rust and Go differ, and the kinds of work each is best suited for.

Rust vs. Go: Performance

On the list of Rust’s major advantages, performance ranks right at the top with safety and ease, and may be the number-one item. Rust programs are designed to run at or near the speed of C and C++, thanks to Rust’s zero-cost runtime abstractions for memory handling and processing.

It’s always possible to write a slow Rust program, but at least you can be sure that Rust is not preemptively sacrificing performance for safety or convenience. What Rust does cost is an effort on the part of the developer to learn and master the language’s abstractions for memory management. (More on memory management below.)

Go, by contrast, does trade some runtime speed for developer convenience. Memory management is handled by the Go runtime (again, more below), so there is an inevitable amount of runtime-associated overhead. But for many scenarios, this trade-off is negligible. Go is by default many times faster than other languages of convenience (e.g., Python).

In short, Rust is faster overall, but for most workaday use cases the difference in speed between Rust and Go will be marginal. In cases where performance is an absolute requirement, Rust can excel in ways that Go cannot.

Rust vs. Go: Memory management

Memory management in Rust and Go are strongly related to the performance behaviors in both languages.

Rust uses compile-time ownership strategies for memory management by way of zero-cost abstractions. This means the vast majority of memory management issues can be caught before a Rust program ever goes live. If a Rust program isn’t memory safe, then it doesn’t compile. Given how much of our world is built atop software that is routinely found to be unsafe due to bad memory management, the Rust approach is way overdue.

As noted above, this safety comes at the cost of Rust’s more challenging learning curve: Programmers must know how to use Rust’s memory management idioms properly, and that requires time and practice. Developers coming from the worlds of C, C++, C#, or Java must rethink how they write code when they sit down with Rust.

Like Rust, Go is memory safe, but that’s because memory management is handled automatically at runtime. Programmers can write thousands of lines of Go code and never once have to think about allocating or releasing memory. Programmers do have some control over the garbage collector at runtime. You can change garbage collection thresholds or trigger collections manually to prevent garbage collection cycles from interfering with operations.

Programmers can also perform some manual memory management in Go, but the language deliberately stacks the deck against doing so. For instance, you can use pointers to access variables, but you can’t perform pointer arithmetic to access arbitrary areas of memory unless you use the unsafe package, an unwise choice for software that runs in production.

If the programming task at hand requires you to allocate and release memory manually—e.g., for low-level hardware or maximum-performance scenarios—Rust is designed to accommodate those needs. Nevertheless, don’t assume that Go’s automatic memory management disqualifies it from creating robust software for your task.

Rust vs. Go: Development speed

Sometimes development speed is more important than program speed. Python has made a career out of being not-the-fastest language to run, but among the fastest languages to write software in. Go has the same appeal; its directness and simplicity make for a speedy development process. Compile times are short, and the Go runtime is faster than Python (and other interpreted, developer-friendly languages) by orders of magnitude.

In short, Go offers both simplicity and speed. So what’s missing? Some features found in other languages (e.g., generics) have been omitted to make the language easier to learn, easier to master, and easier to maintain. The downside is that some programming tasks aren’t possible without a fair amount of boilerplate.

Rust has more language features than Go, and it takes longer to learn and master. Rust’s compile times also tend to be longer than equivalent Go programs, especially for applications with large dependency trees. This remains true even after a concerted effort by the Rust project to shorten compile times.

If a fast development cycle and the need to bring people on board a project quickly are top priorities, Go is the better choice. If you’re less concerned about development speed, and more concerned with memory safety and execution speed, pick Rust.

Rust vs. Go: Concurrency and parallelism

Modern hardware is multi-core, and modern applications are networked and distributed. Languages that don’t plan for these realities are behind the curve. Programmers need to be able to run tasks independently, whether on a single thread or multiple threads, and to share state between tasks without risking data corruption. Rust and Go both provide ways to do this.

Concurrency was baked into the Go language’s syntax from the beginning, by way of goroutines (lightweight threads) and channels (communication mechanisms for goroutines). These primitives make it easy to write applications (such as network services) that must handle many tasks concurrently without risking common issues like race conditions. Go doesn’t make race conditions impossible, but provides native test mechanisms to warn the programmer if race conditions could occur at runtime.

Rust only recently gained native concurrency syntax, in the form of the async/``.await keywords. Before async/.await, concurrency came by way of a crate or package for Rust called futures. Although Rust’s concurrency lacks the years of consolidated developer experience behind Go’s concurrency, it inherits the advantage of Rust’s memory safety—that is, Rust code that could expose race conditions simply won’t compile. Concurrent or asynchronous operations will be harder to write in Rust, due to Rust’s syntax rules, but it will be durable in the long run.

Rust vs. Go: Interoperability with legacy code

New languages like Rust and Go aim for memory safety and programmer convenience in ways that earlier languages didn’t fathom. But the new always has to co-exist to some degree with the old. To that end, Rust and Go both interoperate with legacy C code, although with different restrictions in each case.

Rust can talk directly to C libraries by way of the extern keyword and the libc “crate” (Rust’s name for a package), but all calls to such libraries have to be tagged as unsafe. In other words, Rust can’t guarantee their memory or thread safety; you need to manually ensure that interfaces to C code are safe. Calling into C++ code, on the other hand, isn’t supported at all (at least, not yet) unless said code has a C-compatible interface. Many examples of how to wrap code with Rust’s FFI (Foreign Function Interface)—for C and other languages—can be found at the Rust FFI Omnibus website.

Go provides the cgo package for working with C. The cgo package allows you to call into C libraries, use C header files in your Go code, and convert common data types between C and Go (e.g., strings). However, because Go is memory-managed and garbage-collected, you have to ensure that any pointers you pass to C are handled correctly.

In short, Rust is slightly friendlier regarding C interop than Go, so anything with major dependencies on existing C may tip the scale toward Rust. In both Rust and Go, though, interoperability with C comes at some cost to the developer: more conceptual overhead, slower compile times, more complex tooling, harder debugging.

Note that Rust and Go can always interface with other code at higher levels—e.g., exchanging data via network sockets or named pipes rather than function calls—but these alternatives come at the cost of speed.

Rust vs. Go: Summing up

Choosing between Rust and Go for a software development project is mainly about picking the language that has the qualities you need most for that project. For Rust and Go, you can sum up those qualities as follows.

Rust advantages:

  • Correctness at runtime (common mistakes simply don’t compile)
  • Top-tier execution speed
  • Memory safety without garbage collection
  • Hardware-level code

Go advantages:

  • Quick development cycles
  • High-tier execution speed
  • Memory safety by way of garbage collection
  • Developer convenience
  • Straightforward code

Important Spring Annotations

Spring uses dependency injection to configure and to bring your application together. It means that you just declare the components of your system and how they interact. Then Spring wires it all together at runtime. Here are the most important annotations you should know of.

  • @Configuration - annotation is used to mark a class as a source of the bean definitions. Beans are the components of the system that you want to wire together. A method marked with the @Bean annotation is a bean producer. Spring will handle the life cycle of the beans for you, and it will use these methods to create the beans.
  • @ComponentScan - use to make sure that Spring knows about your configuration classes and can initialize the beans correctly. It makes Spring scan the packages configured with it for the @Configuration classes.
  • @Import - If you need even more precise control of the configuration classes, you can always use @import to load additional configuration. This one works even when you specify the beans in an XML file like it’s 1999.
  • @Component - Another way to declare a bean is to mark a class with a @Component annotation. Doing this turns the class into a Spring bean at the auto-scan time.
  • @Service - Mark a specialization of a @Component. It tells Spring that it’s safe to manage them with more freedom than regular components. Remember, services have no encapsulated state.
  • @Autowired - To wire the application parts together, use the @Autowired on the fields, constructors, or methods in a component. Spring’s dependency injection mechanism wires appropriate beans into the class members marked with @Autowired.

More Complex Spring Annotations

Now it’s time to go a bit deeper. The bean initialization is eager by default. Spring will try to initialize all the beans and wire them all together. You can mark a @Bean or @Component with @Lazy to have them be initialized on demand. It can save some startup time!

If you have multiple beans that can be wired into the field marked with @Autowired, use @Qualifier to filter which beans should be used there.

Another useful annotation is @Value. This one indicates a default value expression for the field or parameter to initialize the property with. Typically something like the following expression, referencing a configuration property will be used there: "#{systemProperties.myProp}".

And to make the system more robust, you can enable the verification to make Spring fail when a bean to autowire is not found. Use @Required to fail the wiring if the dependency cannot be injected.

  • @Lazy - Initialize bean on demand
  • @Value - indicate default value expression for field or parameter
  • @Required - Fail wiring if dependency can’t be injected

Armed with these annotations you can make the application come together with a very little effort. Naturally, there are more Spring annotations that you might want to use, but these here are the core of the framework that enables the flexibility Spring is known for!

Important Spring Boot Annotations

Let’s look at some of the most frequently used annotations in the context of web apps. Most of our readers are either backend engineers or are doing full stack developer jobs. So it makes sense to popularize the Spring Framework annotations that make web development easier.

@SpringBootApplicaiton

First one of the most basic, super helpful annotations, our all time favorite @SpringBootApplication. There’s nothing magical about it. It’s syntactic sugar for combining other annotations that we’ll look at in just a moment. @SpringBootApplication is @Configuration, @EnableAutoConfiguration and @ComponentScan annotations combined, configured with their default attributes.

@Configuration and @ComponentScan

The @Configuration and @ComponentScan annotations that we described above make Spring create and configure the beans and components of your application. It’s a great way to decouple the actual business logic code from wiring the app together.

@EnableAutoConfiguration

Now the @EnableAutoConfiguration annotation is even better. It makes Spring guess the configuration based on the JAR files available on the classpath. It can figure out what libraries you use and preconfigure their components without you lifting a finger. It is how all the spring-boot-starter libraries work. Meaning it’s a major lifesaver both when you’re just starting to work with a library as well as when you know and trust the default config to be reasonable.

Important Spring Boot Web Annotations

The following annotations make Spring configure your app to be a web application, capable of serving the HTTP response.

@Controller

@Controller marks the class as a web controller, capable of handling the HTTP requests. Spring will look at the methods of the class marked with the @Controller annotation and establish the routing table to know which methods serve which endpoints.

@ResponseBody

The @ResponseBody is a utility annotation that makes Spring bind a method’s return value to the HTTP response body. When building a JSON endpoint, this is an amazing way to magically convert your objects into JSON for easier consumption.

@RestController

Then there’s the @RestController annotation – a convenience syntax for @Controller and @ResponseBody together. This means that all the action methods in the marked class will return the JSON response.

@RequestMapping(method = RequestMethod.GET, value = “/path”)

The @RequestMapping(method = RequestMethod.GET, value = “/path”) annotation specifies a method in the controller that should be responsible for serving the HTTP request to the given path. Spring will work the implementation details of how it’s done. You simply specify the path value on the annotation and Spring will route the requests into the correct action methods.

@RequestParam(value=”name”, defaultValue=”World”)

Naturally, the methods handling the requests might take parameters. To help you with binding the HTTP parameters into the action method arguments, you can use the @RequestParam(value=”name”, defaultValue=”World”) annotation. Spring will parse the request parameters and put the appropriate ones into your method arguments.

@PathVariable(“placeholderName”)

Another common way to provide information to the backend is to encode it in the URL. Then you can use the @PathVariable(“placeholderName”) annotation to bring the values from the URL to the method arguments.

Most Useful Spring Cloud Annotations

Now you have a fully functioning web app that is both neat on the code level as well as separated into beans and service classes. The app is declaratively configuring background jobs and gets constructed and configured at runtime without extra uproar.

If you’re in the mood to build a larger system of such web apps, you’ll need to work more on the organizational problems. These include issues like how to configure these multiple apps, how to make them communicate with each other, and how to make sure that network failures will not crash the whole system.

The Spring Cloud project tries to precisely answer these questions and help you take your apps to the cloud.

@EnableConfigServer

@EnableConfigServer turns your application into a server other apps can get their configuration from. You need a configuration server to have a central repository of all the appropriate configurations. The good thing is that creating one is just an annotation away.

Now when you have the central configuration server available, you can use the spring.application.cloud.config.uri property in the client Spring apps to point them to the configuration server. When these apps start, they will reach out to the configuration server and obtain the necessary properties. You don’t have to package your configuration together with the app code. This separation of concerns works wonders to simplify your deployments.


Spring Discovery Service Annotations

The next bit we want to cover is even cooler. Imagine a situation when you have many small services that are context bounded, excel at one thing and put together, form a complex system that brings your real business value. How do you wire the services together? You cannot go with hardcoding the URLs in code or even the configuration – it just won’t scale. What you need is a discovery service.

You probably know where I’m going. You can get yourself a fully functioning Eureka service discovery server just by using a single annotation.

@EnableEurekaServer

Just by adding the @EnableEurekaServer annotation to your brand new Spring Boot app, you make it an Eureka discovery service. Now other apps can locate services through it. To take advantage of this wonderful topology, you need to instruct the apps that they should become clients for this Eureka server.

@EnableDiscoveryClient

Luckily for you, there is a @EnableDiscoveryClient annotation. This makes your app register in the service discovery server and then consult with it to discover the other services you need. When all the apps use the discovery client, you don’t need to hardcode any IP addresses or URLs. You can always say: please Eureka, give me a location of the service by a given name.

@EnableCircuitBreaker

Now with all this fancy distributed system going around, you cannot expect things never to break down. Network can and will fail on you. You need a way to mitigate the damage, and still serve something meaningful back to your clients. So, how can developers ensure resiliency in applications? Resilience patterns.

In this instance, you need a resilience pattern called the circuit breaker pattern. When things go south, you’ll have a way to specify the fallback methods for retrieving data from another service or to respond with reasonable defaults. To make your app aware of the circuit breaker patterns, add the @EnableCircuitBreaker annotation. This will configure Hystrix circuit breaker protocols for your application.

And then mark the important methods with the @HystrixCommand(fallbackMethod = “fallbackMethodName”) annotations. This says that in the case of an emergency when the method throws exceptions or times out, your app should make use of the fallback method. When things are going well, and everything works, this approach will help keep your code neat and maintainable.