Trant
Trant

Reputation: 3611

How to include my class into Spring context?

We're running a Spring setup where I don't see any XML config files, seems everything is done via annotation.

I've got some custom component classes in a specific package I need added to the spring context for autowiring and I annotated the class with @Component but it's not making a difference. Am I missing another annotation?

There is one loop I have where I needed to do a component scan to discover all the classes in the package, maybe I can just add them there since I'd already have a BeanDefinition handle on them. If so, what would I have to do?

for (BeanDefinition bd : scanner.findCandidateComponents("com.blah.target")) {
  // how to add it to context here?
}

Upvotes: 0

Views: 2653

Answers (1)

kajarigd
kajarigd

Reputation: 1309

If you don't see any XML config file, then the project should have a package springconfig with a java file called WebConfig.java. This is exact equivalent of XML config file.

Below is a snippet of a typical Webconfig.java

package .....springconfig;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
<...>


@Configuration
@EnableWebMvc
@ComponentScan(basePackages="<your source package>")
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("home");
    }

    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry){      
          String dir="/resources/"; 
          registry.addResourceHandler("/images/**").addResourceLocations(dir + "images/");
          ...
        }        

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/view/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    @Bean
    public MultipartResolver multipartResolver() {
      CommonsMultipartResolver resolver = new CommonsMultipartResolver();
      resolver.setMaxUploadSize(100);
      return resolver;
    }

}

Check out this tutorial: Simple Spring MVC Web Application It is very nicely explained here.

Upvotes: 1

Related Questions