# 1. 注解
componet,service、controller等注解
# 2. FactoryBean
Spring 为此提供了一个`org.springframework.bean.factory.FactoryBean`的工厂类接口,用户可以通过实现该接口定制实例化`Bean`的逻辑。
1.bean工厂,创建bean对象
~~~
public class StudentFactoryBean implements FactoryBean<Student> {
/**
* 得到自定义对象
*
* @return {@link Student}
* @throws Exception 异常
*/
@Override
public Student getObject() throws Exception {
return new Student("tuna",22);
}
/**
* 得到对象类型
*
* @return {@link Class}<{@link ?}>
*/
@Override
public Class<?> getObjectType() {
return Student.class;
}
}
~~~
2.对象类
~~~
@Data
@AllArgsConstructor
public class Student {
private String name;
private int age;
}
~~~
3.配置factory,此时bean就被创建到容器
~~~
@Configuration
public class config {
@Bean
public StudentFactoryBean getstudentFactory() {
return new StudentFactoryBean();
}
}
~~~
4.test
~~~
@SpringBootTest(classes = {IocApplication.class})
@RunWith(SpringRunner.class)
public class StudentFactoryBeanTest {
@Autowired
private Student student;
@Test
public void test() {
System.out.println(student.getName());
}
}
~~~
输出:tuna
## 3. @Import注解