学习Spring Boot第一天之Spring注解式声明和注入Bean

来源:互联网 发布:美国退出qe 知乎 编辑:程序博客网 时间:2024/05/16 15:19

1、声明Bean

@Component 没有明确的角色

@Service 在业务逻辑层(service层)使用

@Repository 在数据访问层使用(dao层)使用

@Controller 在展现层(MVC→Spring MVC)使用

在类名上使用

2、注入Bean

@Autowired:Spring 提供的注解

@Inject:JSR-330提供的注解

@Resource:JSR-250提供的注解

可在属性、set方法上使用

小测试

DAO层:

@Repository
public class TestDAO {
public String SayHello(String word) {
return "Hello " + word + " !";
}
}

Service层:

@Service
public class TestService {
@Autowired
private TestDAO testDAO;


public String SayHello(String word) {
return testDAO.SayHello(word);
}
}

configuration层:

@Configuration
@ComponentScan("com.liang.springboot.dao01.*")
public class TestConfiguration {
}

main层:

public class TestMain {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
TestConfiguration.class);//AnnotationConfigApplicationContext 作为spring的容器,接受输入一个配置类作为参数
// TestService testService = context.getBean(TestService.class);
TestService testService = (TestService) context.getBean("testService");//和类名相同,首字母小写也可以获得Bean

System.out.println(testService.SayHello("小梁"));
context.close();
}
}


使用@configuration声明当前类为配置类

@CompontScan("包名"),讲自动扫描指定包名下有使用@Service、@component、@repository和@controller的类,并注册为Bean。

原创粉丝点击