九.完全使用注解
1.一个实体类,搞里头
package com.why.bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
/**
* @program: Spring_Study
* @description:
* @author: @why
* @create: 2020-08-13 11:30
**/
@Component
public class User {
private String name;
public User() {
}
public String getName() {
return name;
}
//注入值
@Value("yy")
public void setName(String name) {
this.name = name;
}
public User(String name) {
this.name = name;
}
}
2.一个类,作为一个配置文件等价于之前的xml
package com.why.config;
/**
* @program: Spring_Study
* @description:
* @author: @why
* @create: 2020-08-13 11:31
**/
import com.why.bean.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
//表示这个类被spring注册到了容器中
//并且表示这个是一个配置类 等价于beans.xml
@Configuration
@ComponentScan("com.why.bean")
//加入第二个配置类 放到一起
@Import(config2.class)
public class javaConfig {
//注册一个bean 方法名等价于bean标签中的id 返回值相当于bean标签的class属性
@Bean
public User getUser()
{
return new User();//返回要注入的对象
}
}
3.
//表示这个类被spring注册到了容器中
//并且表示这个是一个配置类 等价于beans.ml
这个也会被Spring容器托管,因为它本来就是一个@Component
扫描所有添加了Component 的实体类
我们可以通过 basePackages 等属性来细粒度地定制 @ComponentScan 自动扫描的范围,如果不指定,则默认 Spring 框架实现会从声明 @ComponentScan 所在类的 package 进行扫描
5.
使用@Scope注解和其再搭配,来说明是否需要单例模式的对象
@Bean("myCar") 给方法起个别名
@Bean(name="person",autowire=Autowire.BY_TYPE)给方法起别名 根据类型自动导入配置
注册一个bean 方法名等价于bean标签中的id 返回值相当于bean标签的class属性
如果一个 bean 的定义依赖其他 bean,则直接调用对应 JavaConfig 类中依赖 bean 的创建方法就可以了。
@Bean
@Scope("prototype")
public User getUser()
{
return new User();//返回要注入的对象
}
等价于
<beans>
<bean id="user" class="com.why.User"/>
</beans>

浙公网安备 33010602011771号