Junior — Middle
How can you identify and register a controller in Spring without using annotations?
sobes.tech AI
Answer from AI
In Spring, you can register a controller without using annotations by utilizing XML configuration or Java configuration with explicit bean declarations.
For example, in XML configuration:
<bean id="myController" class="com.example.MyController" />
In this case, the controller class should implement the appropriate interface or inherit from the necessary class, and routes can be configured through HandlerMapping configuration.
In Java configuration, you can manually create a bean:
@Configuration
public class AppConfig {
@Bean
public MyController myController() {
return new MyController();
}
@Bean
public HandlerMapping handlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
Map<String, Object> urlMap = new HashMap<>();
urlMap.put("/path", myController());
mapping.setUrlMap(urlMap);
return mapping;
}
}
Thus, without annotations, controllers and their routes can be explicitly created and registered through configuration.