DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Languages
  4. Spring Java Config 101

Spring Java Config 101

Jakub Kubrynski user avatar by
Jakub Kubrynski
·
Jan. 24, 14 · Interview
Like (3)
Save
Tweet
Share
29.14K Views

Join the DZone community and get the full member experience.

Join For Free

After my last article there were some questions about how Java configuration work in details, and we can extend it to suit our needs. So I'll try to answer those questions in this post :)

Heart of Spring java configuration mechanism are @Configuration classes. That's the place where we can define all properties of our Spring context.

Assuming that we lean our application on annotations (which should be true if we want to use java config) we create beans using @Component annotation (with derivatives like @Repository,@Service and @Controller). Varying annotations apply for different layers:

@Component generic for any compoenents
@Repository persistence layer
@Service service layer
@Controller presentation layer

Component scanning

After annotating required classes we now want to add them into spring context. To achieve this we have to annotate our @Configuration class by @ComponentScan:

@Configuration
@ComponentScan("my.package.containing.beans")
public class SpringConfig {
}

What is worth considering in this case is a usage of string literals representing packages - it's easy to make a mistake which is hard to find, because even fancy IDE's like IntelliJ won't notice commited typo. Fortunately this annotation brings type-safe alternative which allows us use basePackageClasses parameter to specify for example marker interface lying in desired package.

By default @ComponentScan includes only mentioned earlier annotations but we can easily extend it to use any custom annotation, like for example @ConventionSucks :) It's just needed to addincludeFilters element:

@Configuration
@ComponentScan(basePackageClasses = BeansPackageMarker.class,
includeFilters = @ComponentScan.Filter(ConventionSucks.class))
public class SpringConfig {
}

@ComponentScan.Filter is very generic and it allows using various strategies by type (FilterType) parameter: 

ANNOTATION marked with a given annotation
ASSIGNABLE_TYPE assignable to a given type
ASPECTJ AspectJ type pattern passed by pattern attribute
REGEX uses Pattern class with passed pattern attribute
CUSTOM custom filter implementing TypeFilter


The same filters can be applied to excludeFilters attribute. We have one more attribute which handles filtering - useDefaultFilters turning on importing all objects annotated by @Component with derivatives)

Wiring beans

Now we know how to configure Spring to recognize our beans, but we still haven't covered topic about defining beans dependencies (beans wiring). We can distinguish two cases here:
  • beans that are created by us (we have full control)
  • external beans

User beans

In the case when we're implementing classes we can use @Autowired annotation.
@Component
public class UserBeanB {
private final UserBeanA userBeanA;
@Autowired
public UserBeanB(UserBeanA userBeanA) {
this.userBeanA = userBeanA;
}
}

We can use @Autowired annotation on constructors, fields, methods and annotations. There are many discussions about the best way to inject dependencies, but we won't talk about that in this post.

Instead of Spring specific @Autowired annotation we can use @Inject introduced in JSR-330.

External beans

It's especially important when we integrate some external frameworks or libraries (like for example SpringSecurity)
@Configuration
public class SpringConfig {
@Bean
public ExternalObjectA externalObjectA() {
return new ExternalObjectA();
}
@Bean
public ExternalObjectB externalObjectB1() {
return new ExternalObjectB(externalObjectA());
}
@Bean
public ExternalObjectB externalObjectB2() {
return new ExternalObjectB(externalObjectA());
}
}


Please notice that @Bean annotation on externalObjectA() method is very important even if you don't use this bean outside your configuration class. We you apply @Bean annotation Spring during context loading will discover it and will invoke this method only one (even if we use it many times in configuring our beans). Without this annotation the method will be treated as a normal java method. Also remember that method name will also be used as a bean name.

Joining different configurations

Quite often case while introducing Spring Java Config is when we want to extend working application (for example by introducing new module) or cleaning current configuration, by removing explicitly declared beans. Also in real life solutions we prefer having multiple configuration sources, not just whole big application in one giant class. In such situation what combining many configurations is becoming necessary. Spring brings two solutions:
@Import annotation to import different configuration classes, and
@ImportResource - to import configuration from XML file (you can use prefixes like classpath: or file:)

And that's all - nothing strange ;)
Spring Framework Java (programming language) Annotation

Published at DZone with permission of Jakub Kubrynski, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Is DevOps Dead?
  • Real-Time Analytics for IoT
  • Key Elements of Site Reliability Engineering (SRE)
  • Required Knowledge To Pass AWS Certified Solutions Architect — Professional Exam

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: