1. Use annotations:
In spring's configuration file applicationContext.xml, add annotation scan. The configuration item configures scanning of specified packets to implement dependency injection.
<?xml version="1.0" encoding="UTF-8"?> <span style="font-size:18px;"><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> <aop:aspectj-autoproxy/> <context:annotation-config/> <context:component-scan base-package="com.test" /> //Where to scan</beans>
2. Common comments:
@Controller@Service@Autowired@RequestMapping@RequestParam@ModelAttribute@Cacheable@CacheFlush@Resource@PostConstruct@PreDestroy@Repository@Component (not recommended) @Scope@SessionAttributes@InitBinder@Required@Qualifier
3. Commonly used spring annotations:
@Controller (for presentation layer)
After using @Controller annotation to identify UserAction, it means that the UserAction is to be handed over to the Spring container for management. There will be an action named "userAction" in the Spring container. This name is taken based on the UserAction class name. Note: If @Controller does not specify its value【@Controller】, the default bean name is lowercase in the first letter of the class name. If you specify value【@Controller(value="UserAction")】 or 【@Controller("UserAction")】, then use value as the name of the bean.
The UserAction here also uses the @Scope annotation. @Scope("prototype") means that the scope of the Action is declared as a prototype. You can use the scope="prototype" of the container to ensure that each request has a separate Action to handle it, avoiding the thread safety issues of Action in struts. spring The default scope is singleton mode (scope="singleton"), which will only create an Action object. Each access is the same Action object. The data is not safe. Struts2 requires that each access correspond to a different Action. scope="prototype" can ensure that an Action object is created when there is a request.
@Controller
@Scope("prototype")public class UserAction extends BaseAction<User>{ }@ Service (used in the business logic layer)
Note that the @service annotation is used under the implementation class of the service interface, not in the interface.
This reflects the control inversion in spring very well. We are not letting the object instantiate the object itself and actively rely on the object, but instead use a container to create the object, which is managed by the IOC. Example:
When Action wants to use UserServiceImpl, you don’t have to actively create an instance of UserServiceImpl. Creating a UserServiceImpl instance has been handed over to Spring. Spring gives the created UserServiceImpl instance to Action, and you can use it directly after you get the Action. Action can be used immediately after actively creating the UserServiceImpl instance, but becomes passively waiting for Spring to create the UserServiceImpl instance before injecting it into Action. This shows that Action's "control" over the "UserServiceImpl" class has been "reversed". It turns out that the initiative is in my own hands. I have to use the "UserServiceImpl" class instance. I can take the initiative to use it immediately. But now I cannot take the initiative to new instances of the "UserServiceImpl" class instance. The power of the instance of the new "UserServiceImpl" class has been taken away by Spring. Only Spring can new instances of the "UserServiceImpl" class, and Action can only wait for Spring to create "UserSe" class. After the instance of rviceImpl" class, "please" Spring give it the created instance of the "UserServiceImpl" class so that it can use "UserServiceImpl". This is the core idea of Spring "control inversion", also called "dependence injection". "Dependence injection" is also easy to understand. Action needs to use UserServiceImpl to work, so it creates a dependency on UserServiceImpl. Spring injects (that is, "giving") the UserServiceImpl that the Acion needs to depend on to Action, which is called "dependence injection". For Action, if the Action depends on something, it will ask Spring to inject it. For Spring, what Action needs, Spring will take the initiative to inject it.
@Service("userService")public class UserServiceImpl implements UserService {}@ Repository (for data management)
The author uses the tool to generate the entity layer data Model and mapper in reverse, so this annotation is not used, but this is simply injecting a bean into the spring container.
@Repository(value="userDao")public class UserDaoImpl extends BaseDaoImpl<User> {}4. Commonly used springMVC annotations:
@Autowired (injected by type)
Annotate class member variables, methods and constructors to complete the automatic assembly work. Simply put, it is to call the Bean and tell spring that it exists and is managed in the container.
@Autowired Search from the spring online article according to the bean type. The registration type must be unique, otherwise an exception will be reported.
When the @Autowired annotation acts on the Map type, if the key of the Map is String type, Spring will add all types in the container to the corresponding type of the Map value, and use the bean's id or name as the key of the Map.
@Autowired Another function is that if it is annotated on the BeanFactory type, ApplicationContext type, ResourceLoader type, ApplicationEventPublisher type, and MessageSource type, Spring will automatically inject instances of these implementation classes without additional operations.
@Autowired
private IReportService reportService ;
@Resource (injected by name)
Similar to @Autowired, @Resource searches by default according to the name of the bean. If it is not found, it will search by type.
@Resource
private DataSource dataSource; // inject the bean named 'dataSource'
@Resource(name="dataSource")
@Resource(type=DataSource.class)
Extended question: What is assembly by type and what is assembly by name?
By type means that when there is a bean with the same type as the specified attribute in the Spring container, the attribute will be automatically assembled; if there are multiple beans of this type, an exception will be run and it is pointed out that automatic assembly by type cannot be used; if no matching bean is found, nothing will happen.
The so-called name means automatic assembly based on the attribute name. This item will check the beans in the Spring container that are exactly the same as the attribute name and perform automatic assembly.
@RequestMapping (map request address)
Annotations used to handle requested address mappings can be used on classes or methods. For use on a class, all methods that represent that response requests in a class take this address as the parent path.
There are six attributes, namely:
1. value, method;
value: Specifies the actual address of the request, and the specified address can be in the URI Template mode (which will be explained later);
method: Specify the requested method type, GET, POST, PUT, DELETE, etc.;
2. Consumes, produces
consumers: Specifies the type of submission (Content-Type) that handles the request, such as application/json, text/html;
produces: Specifies the returned content type, which will only be returned if the (Accept) type in the request request header contains the specified type;
3. Params, headers
params: Specifies that the request must contain certain parameter values before the method can be processed.
headers: Specifies that the request must contain some specified header values in order for the method to handle the request.
@Controller@RequestMapping("/bbtForum.do")public class BbtForumController { @RequestMapping(params = "method=listBoardTopic") public String listBoardTopic(int topicId,User user) {}}@RequestMapping("/softpg/downSoftPg.do")@RequestMapping(value="/softpg/ajaxLoadSoftId.do", method=RequestMethod.POST)@RequestMapping(value="/osu/product/detail.do", params={"modify=false"}, method=RequestMethod.POST)@RequestParam (get the value of the request parameter)
For example, our access address in the browser is: localhost:8080/hello?id=1000, and we get the id value, for example:
@RestControllerpublic class HelloController { @RequestMapping(value="/hello",method= RequestMethod.GET) public String saysHello(@RequestParam("id") Integer id){ return "id:"+id; }}@PathVaribale (get data in url)
@RestControllerpublic class HelloController { @RequestMapping(value="/hello/{id}",method= RequestMethod.GET) public String saysHello(@PathVariable("id") Integer id){ return "id:"+id; }}@ResponseBody (return type json)
Function: This annotation is used to convert the object returned by the Controller method into the specified format through the appropriate HttpMessageConverter and write it to the body data area of the Response object.
Time to use: The returned data is not a page with the html tag, but is used when data in some other format (such as json, xml, etc.);
Summarize
The above is the analysis of common annotations in spring springMVC introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!