Starting with Springboot: mistakes I made

As I built many applications before, when I started building with springboot, following the springboot books is not enough for my architectural needs. So, I ran into many critical problems by going beyond those books. I will write them up to help beginners in spring ecosystem like me.

  1. Spring tutorials are not congruent with springboot: Springboot comes with a lot of default configurations which are meant for building web applications. I today added the @EnableWebMvc to my configuration class after reading a spring web mvc tutorial. And suddenly all the Path mapping to my static files were gone and I was getting 404 errors for css and js files! This was because springboot by-default automatically added static files in path before and this annotation actually overrided that configuration! So, if you add that annotation, you also need to add resource handlers for static contents. You can either remove that annotation or follow this article to get it working again:
  2. Session objects couldn’t be cast to the related classes. If got java class cast exceptions even the classes were the same. This happened because of devtools library which reloads the classes during runtime even if the class is not changed! So, the class which was used to create the session attribute object was not the same which I tried to cast to. Two different class object with the same name! So, you need to remove devtools if you are using any kind of serialization and deserialization. Session attributes are serialized when added and deserialized when retrieved when you are using a data store like redis, mongo, etc.
  3. Creating objects with @Autowired properties. I made this mistakes several times. When you create an object, @Autowired won’t work at all. @Autowired only works when beans/objects are created with the spring containers.
  4. Bean generation methods. Springboot will name beans by the method name if you do not specifically provide the name in annotation. I wrote a bean method like this
    public UserHelper getUserHelper() ...

    Then I autowired this bean into other beans as userHelper. And I got nulls. Then I turned on spring actuator and found the bean was named “getUserHelper”! I just changed the method name and made a convention that bean generating methods would have the actual bean name.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s