【Spring第六篇】注解:Annotation
  Cj3kHls43VWD 2023年11月02日 29 0


注解:Annotation


首先不惜在spring容器配置中加上以下字段:

<?xml version="1.0" encoding="UTF-8"?>
<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"
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.xsd">

<!-- 指定要扫描的包-->
<context:component-scan base-package="com.kk"/>

<!-- 开启注解的支持-->
<context:annotation-config/>

</beans>

​<context:component-scan base-package="com.kk"/> 扫面com.kk目录下所有的注解​


​实体类:User​

@Component注解的作用

​在实体类中加上@Component注解,相当于在applicationContext.xml中添加 <bean id="user" class="com.kk.pojo.User"/>​

​其中在实体类中的字段加上值可以使用 @Value(""),相当于 <property name="name" value="赵六"/>​

<bean id="user" class="com.kk.pojo.User"/>
<property name="name" value="赵六"/>
</bean>
//@Component 等价 于 <bean id="user" class="com.kk.pojo.User"/>
//其中id为@Component里边的参数user @Component("user")
@Component
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
// @Value("赵六") 等价 于 <property name="name" value="赵六"/>
@Value("赵六")
public String name;

}

​dao层​

@Repository

​在dao层的接口类中,如果我们想要把其中的类交给spring容器托管,我们可以使用@Repository注解​

import org.springframework.stereotype.Repository;

@Repository
public interface UserDao {
}

​service层​

@Service

​在service层的接口类中,如果我们想要把其中的类交给spring容器托管,我们可以使用@Servicea注解​

@Service
public interface UserService {
}

​controller层​

@Controller

​在controller层中,如果我们想要把其中的类交给spring容器托管,我们可以使用@Controller注解​

@Controller
public class UserControl {
}

测试:

public class Test {
@org.junit.Test
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = context.getBean("user", User.class);
System.out.println(user.getName());
}
}

​tip:​

​ClassPathXmlApplicationContext是spring读取xml最常用的类。而我们一般操作的是ta的接口ApplicationContext。BeanFactory和ApplicationContext区别不大,BeanFactory不在自动BeanPostProcessor和自动 BeanFactoryPostProcessor 上注册。​

【Spring第六篇】注解:Annotation_Spring



【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  dmee7YA5I8o8   2023年11月02日   51   0   0 HTMLxmlJavaScript
  T5djtHPYewvW   2023年11月02日   65   0   0 Javaxml3c
Cj3kHls43VWD
最新推荐 更多