
1.为阅读体验,本站无任何广告,也无任何盈利方法,站长一直在用爱发电,现濒临倒闭,希望有能力的同学能帮忙分担服务器成本
2.捐助10元及以上同学,可添加站长微信lurenzhang888,备注捐助,网站倒闭后可联系站长领取本站pdf内容
3.若网站能存活下来,后续将会持续更新内容
Spring Bean相关的注解主要有@Component, @Controller, @Repository, @Service,@Autowired,@Qualifier,@Configuration,@Value,@Bean,@Scope
@Component, @Controller, @Repository, @Service 有何区别?
这个之前写过了,如下
- @Component,通用的注解,可标注任意类为 Spring 组件。如果一个Bean不知道属于哪个层,通常使用这个。
- @Controller,对应 Spring MVC控制层,主要用户接受用户请求并调用 Service 层返回数据给前端页面。
- @Repostory,对应持久层即 Dao 层,主要用于数据库相关操作。
- @Service,对应服务层,主要涉及一些复杂的逻辑,需要用到 Dao层。
@Autowired 注解有什么作用?
主要用于依赖注入,标注在类的成员变量、方法及构造方法上,将它们依赖的bean注入到类的成员变量、方法及构造方法中,如下,将TestService的bean注入到testService属性中
@Service
public class TestService {
......
}
public class TestController {
@Autowired
private TestService testService;
......
}
@Qualifier 注解有什么作用
@Qualifier通常和@Autowired一起使用,比如当存在多个类型相同的bean时,如果@Autowired采用的是byType时可能会出现混乱,可以搭配@Qualifier使用,只需要在@Qualifier中写上bean的名称即可,如下
@Service("testService1")
public class TestService1 implements TestService{
......
}
@Service("testService2")
public class TestService2 implements TestService{
......
}
public class TestController {
@Autowired
@Qualifier("testService1")
private TestService testService;
......
}
@Configuration注解有什么用?@Bean注解有什么用?
@Configuration
用于定义配置类,可替换xml
配置文件,被注解的类内部包含有一个或多个被@Bean
注解的方法,这些方法将会被AnnotationConfigApplicationContext
或AnnotationConfigWebApplicationContext
类进行扫描,并用于构建bean
定义,初始化Spring
容器。
简单来说就是@Configuration可以看成xml配置文件,@Bean可以看成xml文件中的<bean> </bean>
,具体使用如下
class User{
private String name;
private int age;
public User(String name, int age){
this.name = name;
this.age = age;
}
public void print(){
System.out.println("名字:"+ name + " 年龄:" + age);
}
}
@Configuration
class BeanConfiguration {
@Bean
public User user(){
return new User("路人张",18);
}
}
相当于这玩意
<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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="user" class="dao.User">
<constructor-arg index="0" value="路人张"/>
<constructor-arg index="1" value="18"/>
</bean>
</beans>
@Value注解有什么用?
@Value主要用于对属性赋值,有三种用法
- @Value(“常量”) ,直接赋值常量,包括字符串等
- @Value(“${}”
: default_value
) ,比较常用的读取配置文件 - @Value(“#{}”
? : default_value
),读取注入其他bean的属性或者表达式
举例如下
public class Person {
@Value("路人张") //属性name直接赋值
private String name;
@Value("#{20-2}") //通过表达式对属性age赋值
private Integer age;
@Value("${person.sex}") //获取配置文件中的值对属性sexe进行赋值
private String sex;
}
配置文件的值
person.sex = 男
@Scope注解有什么用?
@Scope用于声明 Spring Bean 的作用域,作用于方法上,bean的作用域有Singleton 、Prototype、Request 、 Session、GlobalSession等,代码如下
@Bean
@Scope("singleton")
public User user(){
return new User("路人张",18);
}
本站链接:https://www.mianshi.online,如需勘误或投稿,请联系微信:lurenzhang888
点击面试手册,获取本站面试手册PDF完整版