public @interface Bean {
//前两个注解可以指定Bean的标识
@AliasFor("name")
String[] value() default {};
@AliasFor("value")
String[] name() default {};
//autowireCandidate 属性来指示该 Bean 是否候选用于自动装配。
//autowireCandidate 属性默认值为 true,表示该 Bean 是一个默认的装配目标,
//可被候选用于自动装配。如果将 autowireCandidate 属性设置为 false,则说明该 Bean 不是默认的装配目标,不会被候选用于自动装配。
boolean autowireCandidate() default true;
//指定初始化方法
String initMethod() default "";
//指定销毁方法
String destroyMethod() default "(inferred)";
}
@Configuration
public class AppConfig {
@Bean("myThing") //指定名称
public Thing thing() {
return new Thing();
}
}
@Configuration
public class AppConfig {
@Bean
public TransferServiceImpl transferService() {
return new TransferServiceImpl();
}
}
<beans>
<bean id="transferService" class="com.acme.TransferServiceImpl"/>
beans>
public class BeanOne {
public void init() {
// initialization logic
}
}
public class BeanTwo {
public void cleanup() {
// destruction logic
}
}
@Configuration
public class AppConfig {
@Bean(initMethod = "init")
public BeanOne beanOne() {
return new BeanOne();
}
@Bean(destroyMethod = "cleanup")
public BeanTwo beanTwo() {
return new BeanTwo();
}
}
可以指定使用 @Bean
注释定义的 bean 应具有特定范围。您可以使用在 Bean 作用域部分中指定的任何标准作用域。
默认作用域为 singleton
,但可以使用 @Scope
注释覆盖此范围,如以下示例所示:
@Configuration
public class MyConfiguration {
@Bean
@Scope("prototype")
public Encryptor encryptor() {
// ...
}
}
public class HappyMachine {
private String machineName;
public String getMachineName() {
return machineName;
}
public void setMachineName(String machineName) {
this.machineName = machineName;
}
}
public class HappyComponent {
//引用新组件
private HappyMachine happyMachine;
public HappyMachine getHappyMachine() {
return happyMachine;
}
public void setHappyMachine(HappyMachine happyMachine) {
this.happyMachine = happyMachine;
}
public void doWork() {
System.out.println("HappyComponent.doWork");
}
}
@Bean
方法中直接调用其他 @Bean
方法来获取 Bean 实例,虽然是方法调用,也是通过 IoC 容器获取对应的 Bean,例如:@Configuration
public class JavaConfig {
@Bean
public HappyMachine happyMachine(){
return new HappyMachine();
}
@Bean
public HappyComponent happyComponent(){
HappyComponent happyComponent = new HappyComponent();
//直接调用方法即可!
happyComponent.setHappyMachine(happyMachine());
return happyComponent;
}
}
package com.alex.config;
import com.alex.ioc.HappyComponent;
import com.alex.ioc.HappyMachine;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* projectName: com.alex.config
* description: 配置HappyComponent和HappyMachine关系
*/
@Configuration
public class JavaConfig {
@Bean
public HappyMachine happyMachine(){
return new HappyMachine();
}
/**
* 可以直接在形参列表接收IoC容器中的Bean!
* 情况1: 直接指定类型即可
* 情况2: 如果有多个bean,(HappyMachine 名称 ) 形参名称等于要指定的bean名称!
* 例如:
* @Bean
* public Foo foo1(){
* return new Foo();
* }
* @Bean
* public Foo foo2(){
* return new Foo()
* }
* @Bean
* public Component component(Foo foo1 / foo2 通过此处指定引入的bean)
*/
@Bean
public HappyComponent happyComponent(HappyMachine happyMachine){
HappyComponent happyComponent = new HappyComponent();
//赋值
happyComponent.setHappyMachine(happyMachine);
return happyComponent;
}
}
@Configuration
public class ConfigA {
@Bean
public A a() {
return new A();
}
}
@Configuration
@Import(ConfigA.class)
public class ConfigB {
@Bean
public B b() {
return new B();
}
}
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigB.class);
// now both beans A and B will be available...
A a = ctx.getBean(A.class);
B b = ctx.getBean(B.class);
}
@Configuration
类。create database studb;
use studb;
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
gender VARCHAR(10) NOT NULL,
age INT,
class VARCHAR(50)
);
INSERT INTO students (id, name, gender, age, class)
VALUES
(1, '张三', '男', 20, '高中一班'),
(2, '李四', '男', 19, '高中二班'),
(3, '王五', '女', 18, '高中一班'),
(4, '赵六', '女', 20, '高中三班'),
(5, '刘七', '男', 19, '高中二班'),
(6, '陈八', '女', 18, '高中一班'),
(7, '杨九', '男', 20, '高中三班'),
(8, '吴十', '男', 19, '高中二班');
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>6.0.6version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.25version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.2.8version>
dependency>
<dependency>
<groupId>jakarta.annotationgroupId>
<artifactId>jakarta.annotation-apiartifactId>
<version>2.1.1version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>6.0.6version>
dependency>
dependencies>
public class Student {
private Integer id;
private String name;
private String gender;
private Integer age;
private String classes;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getClasses() {
return classes;
}
public void setClasses(String classes) {
this.classes = classes;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", gender='" + gender + '\'' +
", age=" + age +
", classes='" + classes + '\'' +
'}';
}
}
//接口
public interface StudentDao {
/**
* 查询全部学生数据
* @return
*/
List<Student> queryAll();
}
//实现类
@Repository
public class StudentDaoImpl implements StudentDao {
@Autowired
private JdbcTemplate jdbcTemplate;
/**
* 查询全部学生数据
* @return
*/
@Override
public List<Student> queryAll() {
String sql = "select id , name , age , gender , class as classes from students ;";
/*
query可以返回集合!
BeanPropertyRowMapper就是封装好RowMapper的实现,要求属性名和列名相同即可
*/
List<Student> studentList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Student.class));
return studentList;
}
}
//接口
public interface StudentService {
/**
* 查询全部学员业务
* @return
*/
List<Student> findAll();
}
//实现类
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDao studentDao;
/**
* 查询全部学员业务
* @return
*/
@Override
public List<Student> findAll() {
List<Student> studentList = studentDao.queryAll();
return studentList;
}
}
@Controller
public class StudentController {
@Autowired
private StudentService studentService;
public void findAll(){
List<Student> studentList = studentService.findAll();
System.out.println("studentList = " + studentList);
}
}
@Configuration
@ComponentScan(basePackages = "com.alex")
@PropertySource("classpath:jdbc.properties")
public class JavaConfig {
@Value("${alex.url}")
private String url;
@Value("${alex.driver}")
private String driver;
@Value("${alex.username}")
private String username;
@Value("${alex.password}")
private String password;
@Bean(destroyMethod = "close")
public DruidDataSource dataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(url);
dataSource.setDriverClassName(driver);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource){
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}
}
public class ControllerTest {
@Test
public void testRun(){
AnnotationConfigApplicationContext applicationContext =
new AnnotationConfigApplicationContext(JavaConfig.class);
StudentController studentController = applicationContext.getBean(StudentController.class);
studentController.findAll();
}
}
<dependency>
<groupId>org.junit.jupitergroupId>
<artifactId>junit-jupiter-apiartifactId>
<version>5.3.1version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>6.0.6version>
<scope>testscope>
dependency>
//@SpringJUnitConfig(locations = {"classpath:spring-context.xml"}) //指定配置文件xml
@SpringJUnitConfig(value = {BeanConfig.class}) //指定配置类
public class Junit5IntegrationTest {
@Autowired
private User user;
@Test
public void testJunit5() {
System.out.println(user);
}
}