企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
Bean 注解可以分成如下两大类。 ``` (1)用于将Java类注册到IoC容器的注解。 @Component: 所有Spring注解的基石,后面见到的所有Spring注解都是基于该注解扩展 @Repository:通常用于dao层 @Service: 通常用于service层 @Controller:通常用于controller层 (2)用于属性注入的注解 @Autowired:根据类型自动装配 @Qualifier:与@Autowired一起使用,实现根据名字自动装配 ``` <br/> 开启 Bean 注解开发步骤如下: **1. maven坐标** ```xml <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> </dependency> ``` **2. 开启包扫描`resources/ApplicationContext.xml`** ```xml <?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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!--开启包扫描,它可以扫描当前包及子包;如果需要扫描多个包,可以使用 , 隔开--> <context:component-scan base-package="learn.springbeananno"/> </beans> ``` **3. 在dao层中使用** ```java /** * (1)如果是 @Repository,则相当于注册 <bean id="userDaoImpl" class="xx.xx.StudentDaoImpl"/> * (2)如果是 @Repository("userDaoImpl2"),则相当于注册 <bean id="userDaoImpl2" class="xx.xx.StudentDaoImpl"/> * <p> * 其中 @Component、@Service、@Controller也是一样的道理 */ @Repository public class UserDaoImpl implements UserDao { @Override public String getUsername() { return "[getUsername]"; } } ``` **4. 在service层中使用** ```java @Service public class UserServiceImpl implements UserService { //装配方式1:按照名称装配 //@Autowired //@Qualifier("userDaoImpl") //private UserDao userDao; //装配方式2:按照类型装配 @Autowired private UserDao userDao; @Override public String getUsername() { return userDao.getUsername(); } } ``` **5. 测试** ```java public class UserTest { private final ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml"); @Test public void testGetUsername() { UserService userService = context.getBean(UserServiceImpl.class); System.out.println(userService.getUsername()); //[getUsername] } } ``` **** 案例源码:https://gitee.com/flymini/codes03/tree/master/learn-springbeananno