相关疑难解决方法(0)

Spring @Autowired用法

在一个将由Spring连接的类中使用@Autowired的优缺点是什么?

为了澄清,我正在谈论@Autowired注释,而不是XML中的自动连线.

我可能只是不理解它,但对我来说它几乎看起来像一个反模式 - 你的类开始意识到它们与DI框架相关联,而不仅仅是POJO.也许我是一个贪婪的惩罚,但我喜欢有bean的外部XML配置,我喜欢有明确的布线,所以我确切知道什么是连线在哪里.

java spring autowired

217
推荐指数
4
解决办法
7万
查看次数

了解spring @Configuration类

了解了Spring @Autowired用法的问题之后,我想为另一个弹簧布线选项(@Configuration该类)创建一个完整的知识库.

假设我有一个如下所示的spring XML文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

  <import resource="another-application-context.xml"/>

  <bean id="someBean" class="stack.overflow.spring.configuration.SomeClassImpl">
    <constructor-arg value="${some.interesting.property}" />
  </bean>

  <bean id="anotherBean" class="stack.overflow.spring.configuration.AnotherClassImpl">
    <constructor-arg ref="someBean"/>
    <constructor-arg ref="beanFromSomewhereElse"/>
  </bean>
</beans>
Run Code Online (Sandbox Code Playgroud)

我该怎么用@Configuration呢?它对代码本身有什么影响吗?

java configuration spring autowired

106
推荐指数
1
解决办法
6万
查看次数

Spring @Autowired是如何工作的

我遇到了一个@Autowired的例子

public class EmpManager {
   @Autowired
   private EmpDao empDao;
}
Run Code Online (Sandbox Code Playgroud)

我很好奇empDao如何得到集合,因为没有setter方法而且它是私有的.

spring dependency-injection autowired

47
推荐指数
2
解决办法
3万
查看次数

Java中@Autowired注释的好处

也许,由于我的英语错误,我无法理解使用@Autowired注释的好处.

根据教程,我们可以通过@Autowired将第一个(I.)案例简化为第二个案例(II.).

我的问题是,@ Autowired是什么意思?因为它不再告诉,因为不使用@Autowired,编译器可以根据声明得出"EmpDao emDao"和"EmpManager"密切相关.

这里引用的代码

一世.

    <bean id="empDao" class="EmpDao" />
    <bean id="empManager" class="EmpManager">
       <property name="empDao" ref="empDao" />
    </bean>

public class EmpManager {

   private EmpDao empDao;

   public EmpDao getEmpDao() {
      return empDao;
   }

   public void setEmpDao(EmpDao empDao) {
      this.empDao = empDao;
   }

   ...
}
Run Code Online (Sandbox Code Playgroud)

II.

<context:annotation-config />

<bean id="empManager" class="autowiredexample.EmpManager" />
<bean id="empDao"     class="autowiredexample.EmpDao" />

import org.springframework.beans.factory.annotation.Autowired;

public class EmpManager {

   @Autowired
   private EmpDao empDao;

}
Run Code Online (Sandbox Code Playgroud)

java spring annotations autowired

11
推荐指数
1
解决办法
2万
查看次数

@autowired on Spring中的方法

我正在学习Spring,据我了解,当我们在具有通用名称的方法(不是setter方法)上使用@annotation时,该方法的参数将自动装配。

public class MovieRecommender {

    private MovieCatalog movieCatalog;

    private CustomerPreferenceDao customerPreferenceDao;

    @Autowired
    public void prepare(MovieCatalog mC,
            CustomerPreferenceDao cPD) {
        this.movieCatalog = mC;
        this.customerPreferenceDao = cPD;
    }

    // ...

}
Run Code Online (Sandbox Code Playgroud)

因此,在这里,将movieCatalogcustomerPreferenceDao字段与mCcPD的值自动关联。我无法理解的是,这与没有“ @autowired ” 的相同方法有何不同

当应用于字段名称时,我理解@autowired,但无法理解何时将值显式传递给方法(setter或任何其他方法),那么Spring有什么特别之处?

java spring annotations autowired

8
推荐指数
3
解决办法
5212
查看次数

Spring Autowire Fundamentals

我是春天的新手,我试图理解下面的概念.

假设这accountDAO是一个依赖AccountService.

场景1:

<bean id="accServiceRef" class="com.service.AccountService">
    <property name="accountDAO " ref="accDAORef"/>
</bean>

<bean id="accDAORef" class="com.dao.AccountDAO"/>
Run Code Online (Sandbox Code Playgroud)

场景2:

<bean id="accServiceRef" class="com.service.AccountService" autowire="byName"/>
<bean id="accDAORef" class="com.dao.AccountDAO"/>
Run Code Online (Sandbox Code Playgroud)

AccountService课堂上:

public class AccountService {
    AccountDAO accountDAO;
    ....
    ....
}
Run Code Online (Sandbox Code Playgroud)

在第二种情况下,如何注入依赖?当我们说它是由Name自动装配时,它究竟是如何完成的.在引入依赖项时匹配哪个名称?

提前致谢!

spring

7
推荐指数
1
解决办法
1万
查看次数

AnnotationConfigApplicationContext尚未刷新

我正在开发一个spring MVC应用程序.当我尝试在我的控制器类中使用AnnotationConfigApplicationContext时,我收到以下错误.我不知道这个陈述究竟意味着什么.

@RequestMapping(value = "/generate", method = RequestMethod.POST)
public ModelAndView generateMappingFile(@ModelAttribute Mapping mapping) 
{
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    MappingFileGenerator mfg = ctx.getBean(MappingFileGenerator.class);
}
Run Code Online (Sandbox Code Playgroud)

错误消息 - >

java.lang.IllegalStateException:org.springframework.context.annotation.AnnotationConfigApplicationContext@116b3c0 has not been refreshed yet
Run Code Online (Sandbox Code Playgroud)

有人能解释我这里出了什么问题吗?我正在使用Spring 4.0.1 ..我是spring mvc的新手.

java spring spring-mvc

7
推荐指数
1
解决办法
1万
查看次数

如何在MockMvc junit测试中将@RestController的ResponseBody作为对象?

我有一个简单的junit测试,用于验证servlet端点的响应.

问题:我想以java对象的形式 获取响应Person,而不是作为string/json/xml表示.

那可能吗?

@RestController
public class PersonController {
    @GetMapping("/person")
    public PersonRsp getPerson(int id) {
        //...
        return rsp;
    }   
}

@RunWith(SpringRunner.class)
@WebMvcTest(value = PersonController.class)
public class PersonControllerTest {
    @Autowired
    private MockMvc mvc;

    @Test
    public void test() {
        MvcResult rt = mvc.perform(get("/person")
                .param("id", "123")
                .andExpect(status().isOk())
                .andReturn();

        //TODO how to cast the result to (Person) p?
    }
}
Run Code Online (Sandbox Code Playgroud)

java junit spring spring-mvc spring-test

5
推荐指数
1
解决办法
2387
查看次数

类不包含用于自动装配的匹配构造函数

我有两节课

public abstract class AbstractDAO<T> {
    private final MyExecutor<T> myExecutor;
    private final Class<T> clazz;

    public AbstractDAO(MyExecutor<T> myExecutor, Class<T> clazz) {
        this.myExecutor = myExecutor;
        this.clazz = clazz;
    }
}
Run Code Online (Sandbox Code Playgroud)

@Component
public class MyDAOImpl extends AbstractDAO<Manager> {
    private final SessionManager sessionManager;
    private final MyExecutor<Manager> myExecutor;

    @Autowired
    public MyDAOImpl(SessionManager sessionManager, MyExecutor<Manager> myExecutor) {
        super(myExecutor, Manager.class);

        this.sessionManager = sessionManager;
        this.myExecutor= myExecutor;
    }
}
Run Code Online (Sandbox Code Playgroud)

我在抽象类的定义中得到一个错误:“类不包含用于自动装配的匹配构造函数”。

我所做的只是向 AbstractDAO 的构造函数添加了一个额外的构造函数参数,它是一个类。我需要这个,因为我没有找到一种方法可以在运行时从 T 中检测到这一点(堆栈流搜索说没有)。

我怎样才能解决这个问题?如何传递只能在实现类中确定的类信息?

非常感谢

java spring dependency-injection

4
推荐指数
1
解决办法
9004
查看次数

我们给spring批注命名是有原因的吗?

我注意到在对spring或spring mvc使用批注时,一些程序员会给批注命名。例如:

@Repository("customerRepository")
public class CustomerRepositoryImpl implements CustomerRepository{
}
Run Code Online (Sandbox Code Playgroud)

我相信该类的功能相同,而没有给出@Repository名称。是否存在将注释命名为有用的情况?

java spring annotations spring-mvc

2
推荐指数
1
解决办法
983
查看次数

使用配置类时的Spring自动装配

我有一个xml bean文件

<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
   <context:annotation-config/>
   <bean id="helloWorld" class="com.a.b.HelloWorld"> 
         <property name="attr1" value="Attr1 from XML"></property>
   </bean>
    <bean id="helloWorld2" class="com.a.b.HelloWorld2">
        <property name="attr2" value="Attr2 from XML"></property>
    </bean>
</beans>
Run Code Online (Sandbox Code Playgroud)

我使用像这样的构造函数自动装配

public class HelloWorld2{
       private String attr2;
       public void setAttr2(String message){
          this.attr2  = message;
       }

       public void getAttr2(){
          System.out.println("getAttr2 == " + attr2);
       }


    }

public class HelloWorld{
       private String attr1;
       private HelloWorld2 helloWorld2;    
       public HelloWorld(){

       }
       @Autowired
       public HelloWorld(HelloWorld2 helloWorld2){
           System.out.println("hhh");
           this.helloWorld2 = helloWorld2;
       }


    public …
Run Code Online (Sandbox Code Playgroud)

java spring autowired

2
推荐指数
1
解决办法
2197
查看次数

使用Spring服务的Builder类

我想在Spring项目中创建一个构建器类(即实现构建器设计模式的类)。问题是我需要构建器使用一些Spring服务。我显然不希望用户在构造函数中显式提供服务,但是当我尝试@Autowire提供服务时,我得到了Autowired members must be defined in valid Spring bean。我可以@Component用来注释我的构建器,但这会使它成为一个单例,这对于构建器而言是不希望的。如何将服务注入我的构建器类而不使其单身?

要使用本文的示例,可以说我有以下构建器:

BankAccount account = new BankAccount.Builder(1234L)
            .withOwner(25324)
            .atBranch("Springfield")
            .openingBalance(100)
            .atRate(2.5)
            .build();
Run Code Online (Sandbox Code Playgroud)

我想withOwner使用UserService给定的ID号作为参数从数据库中获取实际用户。我将如何向构建器注入UserService?

java spring dependency-injection builder autowired

2
推荐指数
1
解决办法
74
查看次数

错误:需要类型为“org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder”的 bean,但无法找到

我想通过创建一个简单的登录屏幕在我的项目中使用 Spring Boot Security,但在运行应用程序时出现这些错误

描述:com.panchmeru_studio.controller.UserController 中构造函数的参数 1 需要类型为“org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder”的 bean,但无法找到。

操作:考虑在配置中定义 org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' 类型的 bean。 这是我的代码。

用户控制器

package com.panchmeru_studio.controller;

import com.panchmeru_studio.entities.ApplicationUser;
import com.panchmeru_studio.repository.ApplicationUserRepository;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UserController {

    private ApplicationUserRepository applicationUserRepository;
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    public UserController(ApplicationUserRepository applicationUserRepository,
                          BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.applicationUserRepository = applicationUserRepository;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @PostMapping("/record")
    public void signUp(@RequestBody ApplicationUser applicationUser) {
        applicationUser.setPassword(bCryptPasswordEncoder.encode(applicationUser.getPassword()));
        applicationUserRepository.save(applicationUser);
    }
}
Run Code Online (Sandbox Code Playgroud)

安全配置.java

package com.panchmeru_studio.security;

import com.panchmeru_studio.filter.AuthenticationFilter;
import com.panchmeru_studio.filter.AuthorizationFilter;

import com.panchmeru_studio.service.ApplicationUserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; …
Run Code Online (Sandbox Code Playgroud)

java spring spring-security spring-boot spring-security-rest

1
推荐指数
1
解决办法
3万
查看次数