Spring针对bean管理中创建对象提供注解
(1)@Component
(2)@Service
(3)@Controller
(4)@Repository
四个注解功能都一样,都可以创建bean实例
基于注解方式实现对象创建
1.引入依赖
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.3.9</version>
</dependency>
2.开启组件扫描
<!-- 开启组件扫描-->
<context:component-scan base-package="com.syw"></context:component-scan>
基于注解方式实现属性注入
(1)@AutoWired : 根据属性类型进行自动装配 步骤(1):创建Service和Dao对象,在Service和Dao类添加创建对象注解 步骤(2):在Service中注入Dao对象,在Service类添加Dao属性,在属性上面使用注解 (2)@Qualifier : 根据属性名称进行注入 (3)@Resource : 根据类型或者名称注入 (4)@Value : 注入普通类型属性完全注解开发
(1)创建配置类,替代xml配置文件package com.syw.spring5.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = {"com.syw"})
public class SpringConfig {
}
(2)编写测试类
@Test
public void testSpringConfig(){
ApplicationContext context = new AnnotationConfigApplicationContext("SpringConfig.class");
UserService userService = context.getBean("userService", UserService.class);
System.out.println(userService);
userService.add();
}
package com.syw.spring5.service;
import com.syw.spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component(value = "userService")
public class UserService {
// 定义Dao类型属性
// 不需要添加set方法
@Autowired
private UserDao userdao;
public void add() {
System.out.println("service add");
userdao.add();
}
}
package com.syw.spring5.dao;
import org.springframework.stereotype.Repository;
@Repository
public interface UserDao {
public void add();
}
package com.syw.spring5.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
@Service
public class UserImpl implements UserDao{
@Override
public void add() {
System.out.println("dao add...");
}
}
单元测试结果为:com.syw.spring5.service.UserService@135606db
service add
dao add...