Annotation is a mechanism similar to comments. Adding annotations to the code can use the information at a later time. Different from annotations, annotations are for us to see. The Java virtual machine will not compile, and annotations will not be compiled, but we can read the information in the annotations through the reflection mechanism. Annotations use the keyword @interface and inherit java.lang.annotition.Annotition
The spring framework provides us with the annotation function.
Using annotation programming is mainly to replace xml files and make development faster. However, the use of xml files is to modify the program to modify the source code. If you don't use xml files now, wouldn't it violate the opening and closing principle? It is true. However, annotations are also better than annotations. Using annotations does not require configuring so many xml files. The most important thing is high development efficiency. .
When annotations are not used, many
The spring framework uses layered annotations.
Persistence layer: @Repository;
Service layer: @Service
Control layer: @Controller
1, to use annotations, you need to add namespace and constraint files to the configuration file
<beans ... xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" ... http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd ">
2, tell the framework which classes use annotations.
<context:component-scan base-package="com.lsz.spring" />
3, persistence layer annotation
Package com.lsz.spring; @Repository public class UserDao{ //。。。。 }
@Repository
is equivalent to
<bean id="userDao" class="com.lsz.spring.UserDao" />
4 in the configuration file, service layer annotation
@Service(value="testService") public classTestService { @Resource//相当于自动装配 private UserDao userDao ; public UserDao getUserDao() { returnuserDao; } public void setUserDao(UserDao userDao) { this.userDao= userDao; } }
<bean id="testService" class="com.lsz.spring.UserService" />
@Controller(value="ua") @Scope(value="prototype") public class UserAction { @Resource private UserService userService ; public UserService getUserService() { returnuserService; } }
@Controller annotation is equivalent to
<bean id="ua" class="com.lsz.spring.UserAction " />
ServletContext application =request.getSession().getServletContext(); ApplicationContextac = WebApplicationContextUtils.getWebApplicationContext(application); UserAction useraction = (UserAction)ac.getBean("ua");//获取控制层对象 response.setContentType("text/html;charset=GBK");//设置编码 PrintWriter out =response.getWriter(); //分别将三个层的对象打印出来。 out.println("Action:"+userAction); out.println("Service:"+userAction.getUserService()); out.println("Dao:"+userAction.getUserService().getUserDao());
The above is the content of spring framework learning (5) annotations. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!