I get userId from request.getRemoteUser(), I want to store it somewhere and get from any layer of application. I don't want to pass the userId from controller to other layers or store it in context. Is there anything similar to this, so that simply autowired userId and use it anywhere.
I'm using Spring-boot and Spring-rest controller.
#Configuration
public class ConfigurationClass {
private #Value("#{ request.getRemoteUser() }") String userId;
#Bean("userId")
#Scope("request")
public String getUserId() {
return userId;
}
Related
I have properties like this:
credentials:
userid: <userid>
password: <password>
I have a POJO:
#Setter
public class Credentials {
private String userid;
private String password;
However, this POJO is in another jar, so I can't add annotations. So I thought I'd try something like this:
#Configuration
#Getter
#Setter
#ConfigurationProperties("credentials")
public class MyCredentials {
private Credentials credentials = new Credentials();
}
But I can't get my class to load the properties. How can I get it to work in this scenario?
Just make a separate configuration bean and access value from that try below code
#Configuration
#Getter
#Setter
#ConfigurationProperties("credentials")
public class MyCredentialSetting{
private String userid;
private String password;
}
Now wherever you want to use just use #Autowired like in controller or service
Here myCredentialSetting has value from propertoes file injected by spring boot automatically
#Autowired
private MyCredentialSetting myCredentialSetting;
String userIdValue=myCredentialSetting.getUserid(); //you will get user id value by this
String password=myCredentialSetting.getPassword();
//Setting value to original pojo for furthur use
private Credentials credentials = new Credentials();
credentials.setUserid(userIdValue);
credentials.setPassword(password);
You are mixing things.
#Setter (and #Getter) are most likely lombok project annotations.
These annotations at compile time will generate the getX() and setX() methods on a Pojo with a property "x".
If the Credentials POJO is in another jar, it should have a getter and setter (or it is not a POJO). So we don't care about lombok.
On another side you have a #Configuration class where Spring boot will create the different beans of your application.
The class should look something like this:
#Configuration
#ConfigurationProperties("credentials")
public class MyCredentials {
#Bean("credentials")
public Credentials credentials(
#Value("${credentials.userid}") String userid,
#Value("${credentials.password}") String password) {
Credentials credentials = new Credentials();
credentials.setUserid(userid);
credentials.setPassword(password):
return credentials;
}
}
With the #Value annotation Spring boot will inject the properties into the method that will create the bean.
EDIT I
As stated by #M.Deinum, the same can be obtained by:
#Configuration
public class MyCredentials {
#Bean("credentials")
#ConfigurationProperties("credentials")
public Credentials credentials() {
return new Credentials();
}
}
#ConfigurationProperties will find the properties prefixed with "credentials" and inject them into the credentials bean.
Thanks for the tip #M.Deinum!
I am working on a spring project where I need to read multiple account credentials (login and password) from application yml file.
I have written the credentials as an associative array like this (I don't know any better way to do it):
app:
mail:
accounts:
- login: firstlogin
password: firstpassword
- login: secondlogin
password: secondpassword
Then I mapped these values to spring application with #Value annotation:
#Service
public class MyClass {
#Values("${app.mail.accounts}")
private List<Map<String, String>> accounts;
...
}
But spring keep throwing an Exception because it fails to read these values.
Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException:
Could not resolve placeholder 'intelaw.mail.accounts' in value "${app.mail.accounts}"
Without changing your application.yml, you can tune your datastructures and make this work.
Create a class Account
class Account {
private String login;
private String password;
//constructors, getters and setters here
}
and read it using a class annotated with #ConfigurationProperties
#Component
#ConfigurationProperties("app.mail")
class MyClass {
private List<Account> accounts = new ArrayList<>();
//getters and setters here
}
and in your service class, you can use it like :
#Autowired
private MyClass myClass;
void someMethod() {
myClass.getAccounts();
}
I have a configuration class like below. All of fields in the inner class OptionalServiceConfigs has a default value as annotated using #Value as shown in below.
Sometimes in my application.properties file, it does not have a single service prefixed property. In that case, we want to have loaded an OptionalServiceConfigs instance with its default field values.
#Configuration
#ConfigurationProperties(prefix = "myconf")
public class MyConfigs {
// ... rest of my configs
#Value("${service:?????}") // what to put here, or can I?
private OptionalServiceConfigs service; // this is null
// In this class all fields have a default value.
public static class OptionalServiceConfigs {
#Value("${mode:local}")
private String mode;
#Value("${timeout:30000}")
private long timeout;
// ... rest of getter and setters
}
// ... rest of getter and setters
}
But unfortunately, the service field is null when it is accessed using its getter method. Because spring boot does not initialize an instance of it when there is no property keys found with prefixed myconf.service.* in my application.properties file.
Question:
How can I make service field to initialize to a new instance along with its specified default field values when there are no corresponding prefixed keys in properties file?
I can't imagine a value to put in annotation #Value("${service:?????}") for service field.
Nothing works, tried, #Value("${service:}") or #Value("${service:new")
Based on #M. Deinum's advice, did some changes to configuration class. I am a newbie to Spring and it seems I have misunderstood how Spring works behind-the-scenes.
First I removed all #Value annotation from inner class (i.e. OptionalServiceConfigs), and as well as service field in MyConfigs class.
Then, initialized all inner class fields with their default values inline.
In the constructor of MyConfigs, I initialized a new instance of OptionalServiceConfigs for the field service.
By doing this, whenever there is no service related keys in my application.properties a new instance has already been created with default values.
When there is/are service related key/s, then Spring does override my default values to the specified values in application.properties only the field(s) I've specified.
I believe from Spring perspective that there is no way it can know in advance that a referencing field (i.e. service field) would be related to the configurations, when none of its keys exist in the configuration file. That must be the reason why Spring does not initialize it. Fair enough.
Complete solution:
#Configuration
#ConfigurationProperties(prefix = "myconf")
public class MyConfigs {
// ... rest of my configs
private OptionalServiceConfigs service;
public static class OptionalServiceConfigs {
private String mode = "local";
private long timeout = 30000L;
// ... rest of getter and setters
}
public MyConfigs() {
service = new OptionalServiceConfigs();
}
// ... rest of getter and setters
}
you can try such a structure which works for me quite fine:
#Data
#Validated
#ConfigurationProperties(prefix = "gateway.auth")
#Configuration
public class AuthProperties {
#NotNull
private URL apiUrl;
#Valid
#NotNull
private Authentication authentication;
#Data
public static class Authentication {
#NotNull
private Duration accessTokenTtl;
#NotNull
private String accessTokenUri;
#NotNull
private String clientId;
#NotNull
private String clientSecret;
#NotNull
private String username;
#NotNull
private String password;
#Min(0)
#NonNull
private Integer retries = 0;
}
}
Important is to have getters and setters in order to enable Spring to postprocess ConfigurationProperties, I am using Lombok (#Data) for this.
please see here for more details:
Baeldung ConfigurationProperties Tutorial
I am trying the Active Record pattern using Spring and Hibernate framework. Below is the description of this pattern:
An object carries both data and behavior. Much of this data is persistent and needs to be stored in a database. Active Record uses the most obvious approach, putting data access logic in the domain object. This way all people know how to read and write their data to and from the database.
So, I removed the traditional Service class and moved its logic and the #Transactional annotation to the entity class. But when I run my application again, the following exception was thrown.
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
org.springframework.orm.hibernate5.SpringSessionContext.currentSession(SpringSessionContext.java:133)
org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:454)
weibo.datasource.UserDao.save(UserDao.java:17)
weibo.domain.User.register(User.java:32)
weibo.web.UserController.register(UserController.java:29)
Source Code
The UserController class:
#PostMapping("/users/register")
public String register(#RequestParam("username") String username,
#RequestParam("password") String password) {
User user = new User(userDao, username, password);
user.register();
return "redirect:/users/login";
}
The User entity class:
#Entity
#Table(name="USERS")
#Transactional
public class User {
#Id
#GeneratedValue
private int id;
private String name;
private String password;
#Transient
private UserDao userDao;
public User() {}
public User(UserDao userDao, String username, String password) {
...
}
public void register() {
userDao.save(this);
}
}
The UserDao class. No #Transactional annotated.
public UserDao(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void save(User user) {
sessionFactory.getCurrentSession().save(user);
}
Why?
UPDATE
As #cristianhh said, the #Transactional annotation must be used in a Spring-Managed bean. However, the entity class is not.
No, while #Transactional is managed by Spring, #Entity is managed by Hibernate.
Hibernate beans are not managed by Spring and respectively not wrappable by the #Transactional annotation.
You can however, use #Transactional in the service/repository layer and wrap a function sending the entity's data access object (DAO).
Hi SO i'm newbie in Vaadin, tries to create form and bind to that POJO object.
...Some declaration
Binder<User> binder = new Binder<>(User.class);
#Autowired
public FormUser(UserRepository userRepository, AuthorityRepository authorityRepository){
this.userRepository = userRepository;
this.authorityRepository = authorityRepository;
authorities = new ListSelect<>("Authorities", authorityRepository.findAll());
authorities.setItemCaptionGenerator(Authority::getAuthority);
//Set items
username.setIcon(FontAwesome.USER);
password.setIcon(FontAwesome.USER_SECRET);
saveButton.addClickListener(e -> {
userRepository.save(user);
});
setSpacing(true);
addComponents(username, password, authorities, saveButton);
binder.bindInstanceFields(this);
}
When try to access view that contains FormUser get this error:
java.lang.IllegalStateException: Property type 'java.util.Collection' doesn't match the field type 'java.util.Set< dev.gva.model.Authority >'. Binding should be configured manually using converter.
Authority :
public class Authority{
private Long id;
private String authority;
getter/setters..
}
User:
public class User{
private Long id;
private Collection<Authority> authorities;
other fields, getters/setters...
}
How to write this converter? Thanks
Instead adding boilerplate code for conversions you should use Set or List for your authorities-attribute within the User-class. An advantage of that would be also that no duplicates are allowed in authorities. The difference between Set and List is that List is ordered and could be accessed by an index. You decide what you need, but Set might be enough.